Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.
js
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
// …
else
statementN
To see how this works, this is how it would look if the nesting were properly indented:
js
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
statement3
// …
The conditions are evaluated in order until one evaluates to true. At that point, the associated statement is executed and the rest of the else if clauses are skipped.
To execute multiple statements within a clause, use a block statement ({ /* ... */ }) to group those statements.
js
if (condition) {
statements1
} else {
statements2
}
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:
js
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
This code looks innocent — however, executing checkValue(1, 3) will log "a is not 1". This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like:
js
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
In general, it is a good practice to always use block statements, especially in code involving nested if statements.
js
function checkValue(a, b) {
if (a === 1) {
if (b === 2) {
console.log("a is 1 and b is 2");
}
} else {
console.log("a is not 1");
}
}
Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false, undefined, null, 0, -0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:
js
const b = new Boolean(false);
if (b) {
console.log("b is truthy"); // "b is truthy"
}