JavaScript If Else

JavaScript if else statements are used to run different blocks of code based on a condition. They help a program decide what to do when a value, user action, comparison, or application state changes.

In JavaScript, conditions are evaluated as either truthy or falsy. If the condition is true, the if block runs. If the condition is false and an else block is present, the else block runs instead.

In this tutorial, we shall learn following statements related to JavaScript If Else.

  • If statement
  • If-Else statement
  • If-Else-If statement
  • Nested If-Else

You will also learn how JavaScript checks conditions, how comparison operators are commonly used inside if statements, when to use else if, and how to avoid common mistakes in conditional logic.

JavaScript If Statement

The JavaScript if statement is used to execute a set of statements only when a condition is true. If the condition is false, the statements inside the if block are skipped.

JavaScript if statement syntax

</>
Copy
if(expression){
    // set of statements
}

Explanation : If expression is true, then set of statements are executed. Else execution continues with the statements after if-statement.

The braces { } define the block of code that belongs to the if statement. Although JavaScript allows a single statement without braces, using braces is safer and clearer, especially when the block is edited later.

JavaScript if statement example

index.html

</>
Copy
<!doctype html>
<html>
<body>
	<h1>JavaScript If Example</h1>
	<p id="message"></p>
	<script>
	<!-- your JavaScript goes here -->
      <!-- try changing the value of "today" and run -->
	  var today='Sunday';
      if(today=='Sunday'){
      	document.getElementById("message").innerHTML = "Today is Sunday.";
      }
	</script>
</body>
</html>

In this example, the message is displayed only when the value of today is equal to 'Sunday'. If you change the value to another day, no message is written because there is no else block.

JavaScript condition using comparison operators

Most JavaScript if else examples use comparison operators inside the condition. The following operators are commonly used with if, else if, and nested if statements.

OperatorMeaning in JavaScript conditionExample
===Strictly equal toage === 18
!==Strictly not equal tostatus !== 'inactive'
>Greater thanmarks > 40
>=Greater than or equal toamount >= 1000
<Less thantemperature < 20
<=Less than or equal toquantity <= 0

For equality checks, prefer === and !== because they compare both value and type. This helps avoid unexpected results caused by automatic type conversion.

</>
Copy
let age = 18;

if (age === 18) {
    console.log("Age is exactly 18.");
}

JavaScript If Else Statement

The JavaScript if else statement is an extension of the if statement. It runs one block of code when the condition is true and another block when the condition is false.

JavaScript if else syntax

</>
Copy
if(expression){
    // set of statements
} else{
    // another set of statements
}

Explanation : If expression is true, then set of statements are executed. Else another set of statements are executed. Either of the two sets of statements shall be executed for sure based on the condition. Execution continues with the statements after if-else statement.

JavaScript if else example

index.html

</>
Copy
<!doctype html>
<html>
<body>
    <h1>JavaScript If Else Example</h1>
    <p id="message"></p>
    <script>
    <!-- your JavaScript goes here -->
    <!-- try changing the value of "today" and run -->
        var today='Monday';
        if(today=='Sunday'){
            document.getElementById("message").innerHTML = "Today is Sunday.";
        } else{
            document.getElementById("message").innerHTML = "Today is not Sunday. You have to go to work.";
        }
    </script>
</body>
</html>

In this example, one of the two messages will always be displayed. If today is 'Sunday', the if block runs. For any other value, the else block runs.

JavaScript if else with logical operators

Logical operators allow you to combine multiple checks inside one JavaScript condition. Use && when all conditions must be true, || when at least one condition must be true, and ! to reverse a Boolean value.

</>
Copy
let isLoggedIn = true;
let hasPermission = false;

if (isLoggedIn && hasPermission) {
    console.log("Show admin page.");
} else {
    console.log("Access denied.");
}

Here, the admin page is shown only when both conditions are true. Since hasPermission is false, the else block runs.

Access denied.

JavaScript If Else If Statement

The JavaScript if else if statement is used when you need to test multiple conditions in sequence. It is useful when there are more than two possible outcomes.

JavaScript if else if syntax

</>
Copy
if(expression){
    // set of statements
} else if(expression_2){
    // another set of statements
} else if(expression_3){
    // another set of statements
} else{
    // default set of statements
}

Explanation : In a sequential order, from top to bottom, the block of statements for which the condition is true is executed. Once the control comes across a condition that is true, rest of the else if blocks are skipped.

There could be as many number of else if blocks as required.

else block is optional. When no condition is satisfied, else is executed.

JavaScript if else if example

index.html

</>
Copy
<!doctype html>
<html>
<body>
    <h1>JavaScript If Else If Example</h1>
    <p id="message"></p>
    <script>
        <!-- your JavaScript goes here -->
        <!-- try changing the value of "today" and run -->
        var today='Tuesday';
        if(today=='Sunday'){
            document.getElementById("message").innerHTML = "Today is Sunday.";
        } else if(today=='Monday'){
            document.getElementById("message").innerHTML = "Today is Monday. You had a wonderful weekend.";
        } else if(today=='Tuesday'){
            document.getElementById("message").innerHTML = "Today is Tuesday. Four more days for the weekend.";
        } else{
            document.getElementById("message").innerHTML = "Hang tight in there. You are about to have a weekend shortly.";
        }
    </script>
</body>
</html>

In an if else if chain, order matters. JavaScript checks the conditions from top to bottom. The first true condition runs, and the remaining conditions are ignored.

JavaScript if else if grading example

The following example uses multiple conditions to assign a grade based on marks.

</>
Copy
let marks = 82;
let grade;

if (marks >= 90) {
    grade = "A";
} else if (marks >= 75) {
    grade = "B";
} else if (marks >= 60) {
    grade = "C";
} else if (marks >= 40) {
    grade = "D";
} else {
    grade = "F";
}

console.log(grade);
B

Because marks is 82, the first condition is false, the second condition is true, and the grade becomes B. JavaScript does not check the remaining else if blocks after that.


JavaScript Nested If Statement

JavaScript If statements could be nested. If statement is like any other JavaScript statement. So it could be one of the ‘set of statements’ inside another if block.

Nested if statements are useful when one condition should be checked only after another condition is already true. However, too many nested levels can make code harder to read, so keep nesting simple when possible.

JavaScript nested if syntax

</>
Copy
if(expression_1){
    // set of statements
    if(expression_2){
        // another set of statements
    }
}

Explanation : If expression_1 is true, control enters the first if block and executes the set of statements. Next if condition is evaluated.

JavaScript nested if example

index.html

</>
Copy
<!doctype html>
<html>
<body>
    <h1>JavaScript Nested If Example</h1>
    <p id="message1"></p>
    <p id="message2"></p>
    <script>
        <!-- your JavaScript goes here -->
        <!-- try changing the value of "today", "holiday" and run -->
        var today='Monday';
        var holiday = true;
        if(today=='Monday'){
            document.getElementById("message1").innerHTML = "Today is Monday.";
            if(holiday){
                document.getElementById("message2").innerHTML = "Its long weekend. There is more fun left.";
            }
        }
    </script>
</body>
</html>

Here, the second condition is checked only when today is 'Monday'. If the first condition is false, JavaScript does not enter the outer if block, so the inner if is not evaluated.

JavaScript truthy and falsy values in if else conditions

A JavaScript condition does not always have to be a comparison such as x === 10. JavaScript can also evaluate a value directly as truthy or falsy.

Common falsy values include false, 0, "", null, undefined, and NaN. Most other values are truthy, including non-empty strings, non-zero numbers, arrays, and objects.

</>
Copy
let username = "";

if (username) {
    console.log("Username is available.");
} else {
    console.log("Username is required.");
}
Username is required.

Because username is an empty string, it is treated as falsy and the else block runs.

JavaScript if else versus ternary operator and switch

JavaScript provides other ways to write conditional logic, but they are not always replacements for if else.

  • Use if else when conditions are complex, involve ranges, or need multiple statements.
  • Use the ternary operator for a short two-way value assignment.
  • Use switch when one expression must be compared against many fixed values.
</>
Copy
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";

console.log(message);

The ternary operator is compact, but it should not be used for long or deeply nested decisions. For readability, use if else when the logic needs more than a simple value choice.

Common mistakes in JavaScript if else statements

  • Using assignment instead of comparison: Write if (x === 10), not if (x = 10).
  • Using loose equality without reason: Prefer === instead of == for predictable checks.
  • Forgetting braces: Always use braces to clearly show which statements belong to the condition.
  • Putting conditions in the wrong order: In an else if chain, place more specific conditions before broader conditions.
  • Overusing nested if blocks: If code becomes deeply nested, consider using logical operators, early returns in functions, or separate helper functions.

JavaScript if else best practices

  • Write conditions that read clearly, such as isLoggedIn or totalAmount >= minimumOrder.
  • Use const and let in new JavaScript code instead of var, unless you are maintaining older code.
  • Prefer strict equality operators === and !==.
  • Keep each branch focused on one clear action.
  • Add an else block when the default case must be handled explicitly.

JavaScript if else reference

For a language reference, you may also read the MDN documentation for JavaScript if…else. For more beginner examples, continue with our JavaScript Tutorial.

Frequently asked questions about JavaScript if else

What is JavaScript if else used for?

JavaScript if else is used to execute one block of code when a condition is true and another block when the condition is false. It is commonly used for validation, user permissions, form handling, messages, calculations, and application flow control.

What is the difference between if and if else in JavaScript?

An if statement runs code only when its condition is true. An if else statement provides two paths: one for a true condition and one for a false condition.

When should I use else if in JavaScript?

Use else if when you need to check multiple related conditions in order. JavaScript runs the first matching branch and skips the remaining else if blocks.

Should I use == or === in JavaScript if conditions?

Prefer === in most JavaScript if conditions because it checks both value and type. The == operator allows type conversion, which can sometimes produce unexpected results.

Can JavaScript if else statements be nested?

Yes. An if or if else statement can be placed inside another if block. This is called nested if. Use it when the inner condition should be checked only after the outer condition is true.

JavaScript if else tutorial QA checklist

  • Confirm that the page explains if, if else, if else if, and nested if as separate JavaScript control-flow patterns.
  • Check that each syntax block uses valid JavaScript structure and the correct PrismJS language class.
  • Verify that output-only blocks use the output class instead of a command or console class.
  • Make sure equality guidance recommends === and !== for normal JavaScript comparisons.
  • Review examples to ensure the condition, executed branch, and skipped branch are explained clearly.

Conclusion

In this JavaScript Tutorial, we have learnt about JavaScript If, JavaScript If-Else, JavaScript If-Else-If, JavaScript Nested If with Syntax and Examples. We also covered comparison operators, logical operators, truthy and falsy values, common mistakes, and best practices for writing readable JavaScript if else conditions.