If-Else-If Statement
In JavaScript, if-else-if statement is used to execute a ladder of conditional code.
Syntax
if (condition1) {
//code
} else if (condition2) {
//code
} else if (condition3) {
//code
} else {
//code
}
where
if
,else
are keywords.condition1
,condition2
,condition3
,… are boolean expressions.code
is any valid JavaScript code.
Any number of else if
blocks are allowed.
else
block is optional.
If condition1
is true, then if-block code is run. If condition1
is false, and condition2
is true, then first else-if-block code is run. If condition2
is also false, and condition3
is true, then second else-if-block code is run. If no condition is true, then else-block code is run.
Examples
1. In the following program, we write an if-else-if statement to check if value in a
is positive, negative, or zero.
a = 10;
if (a > 0) {
console.log("a is positive.");
} else if (a < 0) {
console.log("a is negative.");
} else {
console.log("a is zero.");
}
2. In the following program, we write an if-else-if statement to check if value in supplies
is good(>5), need more supplies(>=0), or if supplies are in deficit(<0).
supplies = 10;
if (supplies > 5) {
console.log("Supplies are good.");
} else if (supplies >=0) {
console.log("Need more supplies.");
} else {
console.log("Deficit in supplies.");
}