Skip to main content
JavaScript Basics
CHAPTER 06 Beginner

JavaScript Conditional Statements

Updated: May 12, 2026
20 min read

# JavaScript Conditional Statements

In real life, we make decisions every day based on conditions: "If it rains, I will take an umbrella; else, I will wear sunglasses." Programming is no different!

In this chapter, we will learn how to make our JavaScript code "think" and make decisions using conditional statements.

1. Introduction

Conditional statements are used to perform different actions based on different conditions. Without them, a program would just run top-to-bottom doing the exact same thing every time. With conditionals, your program can react dynamically to user input, data changes, and environment states.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use the if statement to execute code only when a condition is true.
  • Use the else statement to provide an alternative path.
  • Chain multiple conditions using else if.
  • Use the switch statement for testing a single variable against many values.
  • Nest conditions inside other conditions.
  • Build a working Grade Calculator mini-project.

3. The if Statement

The if statement is the most fundamental decision-making tool. It evaluates a condition (usually wrapped in parentheses). If that condition is true, the code block inside the curly braces {} runs. If it is false, the code block is entirely skipped.

javascript
1234
// Syntax
if (condition) {
    // code to run if condition is true
}

4. The else Statement

What if the condition is false and you want something else to happen? You use the else statement. It catches everything that fails the if test.

javascript
123456
// Syntax
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}

5. The else if Statement

When you have more than two possible outcomes, you use else if. It allows you to chain multiple tests together. The first one that evaluates to true will execute, and the rest will be ignored.

javascript
12345678
// Syntax
if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs if condition1 is false and condition2 is true
} else {
    // runs if all above are false
}

---

6. Real-world Examples & Code Snippets

Example 1: Basic if Statement

javascript
123456
// Example JavaScript
let batteryLevel = 15;

if (batteryLevel < 20) {
    console.log("Battery Low! Please charge your device.");
}

Output Explanation: Because 15 is strictly less than 20, the console will print the warning.

Example 2: if...else Statement

javascript
12345678
// Example JavaScript
let isUserLoggedIn = false;

if (isUserLoggedIn) {
    console.log("Welcome back to your dashboard!");
} else {
    console.log("Please log in or sign up.");
}

Output Explanation: Because isUserLoggedIn is false, it skips the first block and executes the else block.

Example 3: else if Ladder

javascript
12345678910
// Example JavaScript
let currentHour = 14; // 2 PM

if (currentHour < 12) {
    console.log("Good Morning!");
} else if (currentHour < 18) {
    console.log("Good Afternoon!");
} else {
    console.log("Good Evening!");
}

Output Explanation: 14 is not less than 12, so it checks the else if. 14 IS less than 18, so it prints "Good Afternoon!" and ignores the rest.

Example 4: Nested Conditions

You can place if statements inside other if statements. This is called nesting.

javascript
12345678910111213
// Example JavaScript
let isOnline = true;
let hasCredits = false;

if (isOnline) {
    if (hasCredits) {
        console.log("You can download the file.");
    } else {
        console.log("You are online, but you don&#039;t have enough credits.");
    }
} else {
    console.log("You are offline. Please connect to the internet.");
}

Output Explanation: First it checks if the user is online (True). Then it goes inside and checks if they have credits (False). It executes the inner else block.

Example 5: Using Logical Operators with if

Instead of nesting, we can often use Logical AND (&&) to combine conditions.

javascript
123456789
// Example JavaScript
let age = 25;
let hasLicense = true;

if (age >= 18 && hasLicense === true) {
    console.log("You are legally allowed to drive.");
} else {
    console.log("You cannot drive.");
}

Example 6: The switch Statement

When you need to test a single variable against many specific values, switch is much cleaner than writing ten else if statements.

javascript
12345678910111213141516171819202122232425
// Example JavaScript
let dayOfWeek = 3;
let dayName;

switch (dayOfWeek) {
    case 1:
        dayName = "Monday";
        break; // Break stops the code from bleeding into the next case
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    default:
        dayName = "Weekend!"; // Default is like the 'else' catch-all
}

console.log("Today is: " + dayName);

Output Explanation: Checks dayOfWeek. It matches case 3, assigns "Wednesday" to the variable, hits break, and exits the switch statement.

Example 7: The Importance of break in Switch

If you forget the break keyword, the code will "fall through" and execute the remaining cases even if they don't match!

javascript
1234567891011
// Example JavaScript
let fruit = "apple";

switch (fruit) {
    case "apple":
        console.log("Apples are $1.00");
        // Oops, forgot to break!
    case "banana":
        console.log("Bananas are $0.50");
        break;
}

Output Explanation: It will print BOTH prices. Apples are $1.00 AND Bananas are $0.50. This is a very common bug!

Example 8: Checking for Data Types

Remember that inputs from HTML are strings.

javascript
12345678
// Example JavaScript
let input = "10";

if (input === 10) {
    console.log("It&#039;s a true number!");
} else if (input == 10) {
    console.log("It&#039;s a string that looks like a number!");
}

Output Explanation: The strict equality (===) fails because "10" (string) is not 10 (number). It hits the else if and succeeds.

Example 9: Truthy and Falsy Values

In JavaScript, you don't always have to use ==. Some values are naturally evaluated as false when put inside an if() statement. These are called Falsy values: 0, "" (empty string), null, undefined, NaN, and false. Everything else is Truthy.

javascript
12345678
// Example JavaScript
let userName = "";

if (userName) {
    console.log("Hello, " + userName);
} else {
    console.log("Please enter a username!"); // This runs because "" is falsy
}

Example 10: Early Return Pattern (Advanced Best Practice)

Instead of huge nested if/else blocks inside functions, developers often return early to keep code clean.

javascript
1234567891011
// Example JavaScript
function checkAccess(userAge) {
    if (userAge < 18) {
        return "Access Denied!"; // Function completely stops here
    }
    
    // We only get here if they are 18 or older. No 'else' needed!
    return "Access Granted!";
}

console.log(checkAccess(15));

---

7. Common Mistakes for Beginners

  1. 1. Using = instead of ===: if (x = 10) assigns 10 to x. It does NOT check if x equals 10. Always use ===.
  1. 2. Forgetting curly braces {}: While technically JavaScript allows single-line if statements without braces, it is a terrible habit that leads to bugs when you try to add a second line of code later.
  1. 3. Forgetting break in a switch statement: As shown in Example 7, this causes logic to bleed into places it shouldn't.

8. Best Practices

  • Always use curly braces {} even for single-line if-statements to maintain readability.
  • If you have more than 4 else if conditions checking the exact same variable against specific values, switch to a switch statement.
  • Keep nesting to a minimum. If you have an if inside an if inside an if, try combining them with && to make the code cleaner.

9. Mini Project: Grade Calculator

Let's build an app where a teacher types in a numerical score, and the JavaScript logic calculates their letter grade.

HTML:

html
12345678910111213141516171819202122232425
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; display: flex; justify-content: center; margin-top: 50px; }
        .card { padding: 20px; border: 1px solid #ccc; border-radius: 8px; box-shadow: 2px 2px 10px rgba(0,0,0,0.1); width: 300px;}
        input, button { width: 100%; margin-top: 10px; padding: 10px; box-sizing: border-box; }
        button { background: #28a745; color: white; border: none; cursor: pointer; font-size: 16px; }
        #gradeResult { font-size: 24px; font-weight: bold; text-align: center; margin-top: 15px; }
    </style>
</head>
<body>

    <div class="card">
        <h2>Grade Calculator</h2>
        <input type="number" id="scoreInput" placeholder="Enter score (0-100)">
        <button onclick="calculateGrade()">Get Grade</button>
        <div id="gradeResult"></div>
    </div>

    <script src="grades.js"></script>
</body>
</html>

grades.js:

javascript
123456789101112131415161718192021222324252627282930
// Example JavaScript
function calculateGrade() {
    let score = Number(document.getElementById("scoreInput").value);
    let resultElement = document.getElementById("gradeResult");

    // Input Validation
    if (score < 0 || score > 100) {
        resultElement.innerHTML = "Invalid Score!";
        resultElement.style.color = "red";
        return; // Stop execution
    }

    // Logic using else if
    if (score >= 90) {
        resultElement.innerHTML = "Grade: A";
        resultElement.style.color = "green";
    } else if (score >= 80) {
        resultElement.innerHTML = "Grade: B";
        resultElement.style.color = "blue";
    } else if (score >= 70) {
        resultElement.innerHTML = "Grade: C";
        resultElement.style.color = "orange";
    } else if (score >= 60) {
        resultElement.innerHTML = "Grade: D";
        resultElement.style.color = "brown";
    } else {
        resultElement.innerHTML = "Grade: F (Fail)";
        resultElement.style.color = "red";
    }
}

10. Exercises

  1. 1. Write an if statement that checks if a variable temperature is strictly greater than 30. If it is, console log "It's hot outside".
  1. 2. Write an if...else block that checks if a variable isWeekend is true. If true, print "Relax", otherwise print "Go to work".
  1. 3. Convert the following logic to a switch statement: If status is "success", print "Green". If "error", print "Red". If "warning", print "Yellow".

11. MCQs (Multiple Choice Questions)

Q1: Which of the following is considered a "Falsy" value in JavaScript? A) "false" (string) B) 1 C) 0 D) [] (empty array) *Answer: C (0 is mathematically falsy. "false" as a string is truthy!)*

Q2: What keyword is used to stop a switch statement from bleeding into the next case? A) stop B) exit C) return D) break *Answer: D*

Q3: If x = 5, what will if (x = 10) evaluate to? A) true B) false C) error *Answer: A (Because assigning a truthy value like 10 evaluates to true. This is why you must use ===)*

12. Interview Questions

Q: Can you explain the concept of Truthy and Falsy values? *A: In JavaScript, every value has an inherent boolean state. Falsy values evaluate to false when placed in a boolean context (like an if statement). The only falsy values are false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN. Everything else is truthy.*

Q: When should you use a switch statement instead of if...else? *A: A switch statement is best used when you are testing a single expression or variable against multiple distinct, specific, constant values. It makes the code more readable and can sometimes be slightly more performant than a long chain of else if statements.*

13. FAQs

Q: Do I have to write else after an if? *A: No. You can write an if statement entirely on its own. If the condition is false, the program simply moves on to the next line of code below the if block.*

14. Summary

  • if evaluates a condition.
  • else provides a fallback if the condition is false.
  • else if allows you to chain multiple checks.
  • switch is great for checking one variable against many specific values.
  • Remember to use break inside switch cases!
  • Input validation (checking if the user's data makes sense) is a crucial part of conditional logic.

15. Next Chapter Recommendation

Making decisions is great, but what if we need to do something 100 times? Copy-pasting code 100 times is terrible. In the next chapter, JavaScript Loops, we will learn how to automate repetitive tasks effortlessly.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·