If else in JavaScript | Nested if else, Example

If else in JavaScript is a two-way conditional statement or double selection statement. It tests a condition and executes one of two sets of code, depending on the result.

In other words, if else statement executes the first statement if the condition is true. Otherwise, it executes the second statement if the condition is false. It decides the execution path based on whether the condition is true or false.

A one-way if statement executes a statement if and only if the specified condition is true. If the condition is false, nothing will be done.

But, assume we want to take alternative action when the specified condition is false. In this case, we will use a two-way if-else statement.

The double selection if-else statement in JavaScript routes the execution through two different paths based on the outcome of the condition.

Syntax of If else statement in JavaScript


The syntax of using if else statement in JavaScript is as follows:

if(expression or condition)
{
    statement to be executed if the condition is true.
}
else {
     statement to be executed if the condition is false.
}

In the above syntax, the expression may be any comparison or logical expression that returns either true or false. Each statement represents a single statement or a block of statements enclosed in curly braces ( { }).

If the boolean expression returns true, JavaScript interpreter executes the block of statements. If it returns false, JavaScript interpreter executes the block of statements.

The else clause is an optional part. It means that else clause part can be omitted if not required. You can follow this convention in ​all control statements in JavaScript.

Flowchart Diagram of If else statement


The flowchart for two-way if-else statement is as shown below in the figure.

JavaScript If-else flowchart diagram

Let’s understand with the help of flowchart diagram how two-way if-else statements work in JavaScript.

If the condition in the parentheses is true, then the conditional code within if block will execute. If the condition is false, the else code will execute. In no case will both statements execute at a time.


For example, consider the following code.

let passMarks = 40;
if(passMarks >= 40) {
   document.write("Passed")
}
else {
   document.write("Failed")
}

In the above example, if the boolean expression evaluates to true i.e., if the passMarks is greater than or equal to 40, is true, and it will display a message “Passed” on the browser. If it is false, the message “Failed” will display.

As usual, you can omit braces if there is only one statement within the block.

Substitution of If-else statement with Conditional operator

We can also replace if-else statement with conditional operator (?:). Consider the following statement.

document.write(passMarks >= 40 ? "Passed" : "Failed");

This statement contains the conditional expression that evaluates to the string “Passed” if the condition is true. If the condition is false, it evaluates to the string “Failed”.


Thus, this statement with conditional operator performs the same function as the preceding if-else statement.


Let’s consider another example of using the if-else statement. This example will verify whether a number is even or odd. The code is as follows:

if (number % 2 == 0)
     document.write(number + " is even.");
else
    document.write(number + " is odd.");

Some valid if else statements are as follows:

1. if(x > y)
         document.write(x+ " is greater than " +y);
    else
        document.write(y+ " is greater than " +x);

2. if((gender == 'M') || (gender == 'm'))
          document.write("You are a male");
    else
          document.write("You are a female");

JavaScript If else Example Program for Best Practice


Let’s practice some example programs based on if-else statement in JavaScript.

1. Let’s create a very simple program in which we will take marks of three subjects and then calculate the total marks, percentage, and grade using if else statement.

Program code 1:

<script>
  let chem, phy, maths;
  chem = 96;
  phy = 70;
  maths = 80;
  let total = chem + phy + maths;
  let per = total/3;

  document.write("Total: " +total, "<br>");
  document.write("Percentage: " +per, "<br>");
  if(per >= 80)
      document.write("Grade A");
  else
      document.write("Grade B");
</script>
Output:
     Total: 246
     Percentage: 82
     Grade A

2. Let’s take another example program, where we will take two numbers, and check that number is even or odd. For example, if we take a number 20, then it will display “Number 20 is even”. If we take 21, it will display “Number 21 is odd”. Let’s write code for it.

Program code 2:

<script>
   let num1, num2;
   num1 = 20;
   num2 = 21;
   if(num1 % 2 == 0) {
       document.write("Number " +num1+ " is even", "<br>");
   }
   else {
        document.write("Number " +num1+" is odd", "<br>");
    }

   if(num2 % 2 == 0) {
     document.write("Number " +num2+ " is even", "<br>");
   }
   else {
     document.write("Number " +num2+" is odd", "<br>");
   }
</script>
Output:
    Number 20 is even
    Number 21 is odd


3. Let’s write JavaScript code to check whether a number is divisible with another number or not. Print appropriate message.

Program code 3:

<script>
   let num1, num2;
   num1 = 20;
   num2 = 7;
   if(num1 % num2 == 0) {
      document.write(num1+ " is divisible by " +num2);
   }
   else {
      document.write(num1+ " is not divisible by " +num2);
   }
</script>
Output:
     20 is not divisible by 7

4. Let’s write JavaScript code to take a number and check whether it is a Buzz number or not. A number is a buzz number when it ends with 7 or is divisible by 7.

Program code 4:

<script>
  let num = 777;
  if((num % 10 == 0) || (num % 7 == 0))
      document.write(num+ " is a Buzz number ");
  else
      document.write(num+ " is not a Buzz number");
</script>
Output:
      777 is a Buzz number

5. Let’s write JavaScript code in which we will increment the salary of employee 10% if the salary is greater than 5000. If the salary of employee is less than 5000, will increment 20%.

Program code 5:

<script>
   let salary = 7000;
   if(salary >= 5000)
  {
     salary = salary + (salary * 0.1);
     document.write("Employee salary: " +salary);
   }
  else
  {
     salary = salary + (salary * 0.2);
     document.write("Employee salary: " +salary);
   }
</script>
Output:
      Employee salary: 7700

In the above example program, the variable salary has initialized with the value 7000. Then, the if else statement will check that the salary is greater than 5000 or not.

If the salary is greater than 5000, it will increment by 10% and display in the browser. However, if the condition does not satisfy, the else block will execute. In this case, salary will increment by 20% and display in the browser.

Nested if else Statement in JavaScript


When an “if statement” is declared inside another if statement or if else statement, it is called nested if else statement in JavaScript. The inner if statement can also have another if statement.

Nested if else statement is a very common to use in JavaScript programming. The general syntax for using JavaScript nested if else statements with an example are as follows:

// Outer if statement.
if(condition-1) {
// Inner if statement declared in outer if else statement.
     if(condition-2) {
         statement1;
     }
  }
// Else part of outer if statement.
   else {
       statement2;
    }

In the above syntax, first, condition-1 will evaluate and if it is true, the inner if block will execute. If condition-1 is false, else part of outer if statement will execute and inner if block will skip.

Consider the example of nested if else statement.

if (x > y)
{
// Inner if statement declared in outer if else statement.
     if (y > z)
            document.write("x is greater than y and z"); // statement1.
}
else {
    document.write("x is less than or equal to y"); // statement2.
}

In this example, if x is greater than y and y is greater than z, statement1 will execute. If x is greater than y but y is not greater than z then statement1 will not execute. In this case, else part (i.e., statement2) will execute.


6. Let’s take an example program based on nested if statements in JavaScript.

Program code 6:

<script>
   let x = 2, y = 3, z = 1;
// Outer if statement.
    if(x == 2)
   {
// First inner if statment inside outer if statement.
    if(y < 5) {
       document.write("ABC", "<br>");
    }
// Second inner if-else statement inside outer if statement.
    if(z > 3)
        document.write("DEF", "<br>");
    else
        document.write("PQR", "<br>");
    }
// Else part of outer if statement.
   else {
     document.write("XYZ");
   }
</script>
Output:
      ABC
      PQR

In this example program, since x is equal to 2 and y is less than 5, therefore, the result will display “ABC”. In the second inner if-else statements, z is not greater than 3, therefore, else part of inner if else will execute and display “PQR”.

Suppose x is not equal to 2 in the above example. In this case, inner nested if statements will not execute, and else part of outer if statement will execute. As a result, “XYZ” will display.

If-else if Ladder Statements in JavaScript


If-else if ladder in JavaScript is a multi-way decision structure that we can use to decide among three or more actions.

The general syntax for if-else if ladder statements in JavaScript are as follows:

if(condition-1)
       statement1; // It will execute if condition-1 is true.
else if(condition-2)
       statement2; // It will execute if condition-2 is true.
else if(condition-3)
       statement3;
...
...
else if(condition-n)
      statementn; // It will execute if condition-n is true.
else
    statement; // It will execute if none of the condition is true.

In the above syntax, there may be more than one else if clauses and the last else clause is optional.

How if-else if Ladder works in JavaScript


The flowchart diagram for JavaScript if-else if ladder has shown in the below figure.

JavaScript if-else if ladder flowchart diagram

If-else if ladder works in the following steps that are, as follows:

1. The first specified condition-1 evaluates to true. If the condition is true, statement1 inside if block will execute and the rest part of else if ladder will skip.

2. If the specified condition-1 is false, the second if condition-2 evaluates to true. The second condition-2 is true, statement2 will execute, and the rest part of the ladder will bypass.

3. If the second condition-2 is false, the third condition-3 and the rest of the conditions (if required) will evaluate (or test) until a condition meets or all of the conditions prove to be false.

4. If all the conditions are false, the final else block (i.e., statement) associated with the top if statement will execute.

5. The statement associated with final else block acts as a default condition. That is, if all of the above conditional tests fail, the statement associated with the last else will execute.

If there is no final else block and none of the conditions is true, in this case, no action will take place.


Note: A condition will evaluate only when all the conditions that come before it are false.

If-else if Ladder Example Program for best Practice


7. Let’s write JavaScript code in which we will add marks of 3 subjects and calculate percentage and grade according to percentage using JavaScript if-else-if ladder.

Program code 7:

<script>
   let eng, science, maths;
   eng = 80;
   science = 90;
   maths = 95;
   let total = eng + science + maths;
   let per = total/3;
   document.write("Total marks: " +total, "<br>");
   document.write("Percentage: " +per, "<br>")

   if (per >= 90.0)
         document.write("Grade A");
   else if (per >= 80.0)
         document.write("Grade B");
   else if (per >= 70.0)
         document.write("Grade C");
   else if (per >= 60.0)
         document.write("Grade D");
   else
         document.write("Grade F");
</script>
Output:
      Total marks: 265
      Percentage: 88.33333333333333
      Grade B

Since the percentage 88.33 is less than 90, the first condition will be false. Therefore, the second condition will check. As the percent 88.33 is greater than 80%, Grade B will display and the rest of the else if ladder will skip.


8. Let’s consider an example program in which we will take the age of the user as input and find whether he is a child, adult, or senior on the basis of age. Using JavaScript if-else-if ladder statements.

Program code 8:

<script>
   let age;
   age = prompt("Enter your age: ");
   if (age < 18)
        document.write("Child");
   else if ((age >= 18) && (age <= 60))
        document.write("Adult");
   else if (age >= 60)
        document.write("Senior");
   else
        document.write("Invalid age");
</script>
Output:
     Enter your age: 
     20
     Adult

In this tutorial, you learned if else statement in JavaScript with example program. Hope that you will have understood the basic concepts of nested if else statement and if-else if ladder.
Thanks for reading!!!
Next ⇒ Switch Statement in JavaScript⇐ PrevNext ⇒

Please share your love