The Else If in JavaScript is instrumental when we have to check several conditions. We can also use Nested If to achieve the same. Still, as the number of conditions increases, code complexity will also increase. The syntax of Else If in Javascript is as follows:
if (condition 1) statements 1 else if (condition 2) statements 2 else if (condition 3) statements 3 ........... else if (condition n) statements n else default statements
The JavaScript Else If statement handles multiple statements effectively by executing them sequentially. It will check for the first condition. If the condition is TRUE, then it will execute the statements present in that block. If the condition is FALSE, then it will check the Next one (Else If condition) and so on.
There will be some situations where condition 1, condition 2 is TRUE, for example:
x = 20, y = 10
Condition 1: x > y //TRUE
Condition 2: x != y //TRUE
In these situations, statements under Condition 1 will execute. Because JScript ELSE IF conditions will only execute if it’s previous IF or ELSE IF statement fails.
Else If in JavaScript Flow Chart
Let us see the flow chart of JavaScript Else If for better understanding.
Else If in JavaScript Example
In this program, We are going to calculate whether he is eligible for scholarship or not using JavaScript Else if statement
<!DOCTYPE html> <html> <head> <title> Else If in JavaScript </title> </head> <h1> Else If in JavaScript </h1> <body> <script> var Totalmarks = 380; if (Totalmarks >= 540) { document.write("<b> Congratulations </b>"); document.write("<br\> You are eligible for Full Scholarship " ); } else if(Totalmarks >= 480) { document.write("<b> Congratulations </b>"); document.write("<br\> You are eligible for 50 Percent Scholarship " ); } else if (Totalmarks >= 400) { document.write("<b> Congratulations </b>"); document.write("<br\> You are eligible for 10 Percent Scholarship " ); } else { document.write("<b> You are Not eligible for Scholarship </b>"); document.write("<br\> We are really Sorry for You" ); } </script> </body> </html>
OUTPUT 1: In this JScript example, the Totalmarks = 550. First If condition is TRUE that’s why statements inside the If Statement displayed as Browser output
OUTPUT 2: To demonstrate the JavaScript Else if statement, we are going to change the Totalmarks to 500 means first IF condition is FALSE. It will check the else if (Totalmarks >= 480), which is TRUE, so that it will display the statements inside this block. Although else if (Total marks >= 400) condition is TRUE, but it won’t check that condition.
OUTPUT 3: We are going to change Totalmarks to 440 means first IF condition, else if (Total marks >= 480) are FALSE. So, It will check the else if (Totalmarks >= 400), which is TRUE, so that it will print the code inside this block.
OUTPUT 4: We are going to change Totalmarks to 380 means all the IF conditions Fail. So, It will print the code inside the else block.