if
statement
JavaScript has a if statement similar to languages like Java and C++, except that the condition of an if statement can be anything that can be coerced to a boolean value (see the previous section on Boolean-ish values)
if (condition) {
// statements
}
The statements inside an if block can contain other control structures, including other if statements (nested if statements).
const age = 17; if (age >= 13) { if (age <= 19) { console.log("You are a teenager!"); } }
An if condition can be expanded with an else block
const num = 37; if (num % 2 === 0) { // check if num is even console.log(num + " is even!"); } else { console.log(num + " is odd!"); }
If you have only one statement, the braces around that statement are optional. Consider it good practice to always include braces.
const age = 12; if (age >= 13) if (age <= 19) console.log("You are a teenager!"); else console.log("You are NOT a teenager!"); // The else is paired with the nearest if // unless you enclose the second if in brackets.
You can chain several if statements:
const score = 73; // Convert score to letter grade if (score >= 85) { console.log("Grade: A"); } else if (score >= 70) { console.log("Grade: B"); } else if (score >= 55) { console.log("Grade: C"); } else { console.log("Grade: F"); }
The if
-else
-if
ladder exits at the first success. If the conditions overlap, the first criteria occurring in the flow of execution is executed.
Ternary operator
Consider the following expression that uses the ternary operator ?
:
let max = a > b ? a : b;
which is the same as
let max;
if (a > b) {
max = a;
} else {
max = b;
}