Use the if else if statement if you want to check 2 conditions in JavaScript. Use if
to specify a block of code to be executed, if a specified condition is true.
And Use else if
to specify a new condition to test, if the first condition is false
if (condition) {
// statement
} else if(condition){
// statement
}else{
// statement
}
Here’s a breakdown of how these statements work:
- The
if
statement checks the condition specified in its parentheses. If the condition is true, the code block within the first set of curly braces is executed. If the condition is false, the code block is skipped. - If you have additional conditions to check, you can use
else if
. Eachelse if
statement allows you to check a new condition if the previous conditions were false. The code block within the curly braces of the firstelse if
that evaluates to true will be executed. - You can end the conditional structure with an
else
statement. If none of the previous conditions are evaluated to true, the code block within theelse
statement’s curly braces will be executed. It acts as a fallback option when none of the earlier conditions are met.
Example if else if JavaScript
A simple example code uses the else if
statement to specify a new condition if the first condition is false.
<!DOCTYPE html>
<html>
<body>
<script>
var greeting= "Hello"
var time = 15;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting)
</script>
</body>
</html>
Output:
Multiple if...else
statements can be nested to create an else if
clause.
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
...
else
statementN
Here’s an example that demonstrates the usage of if
, else if
, and else
:
let num = 42;
if (num < 0) {
console.log("The number is negative.");
} else if (num === 0) {
console.log("The number is zero.");
} else {
console.log("The number is positive.");
}
Do comment if you have any doubts or suggestions on this JS if else topics.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version