Conditional Statements
JavaScript’s control flow statements are similar to the ones in other programming languages.
if…else statement
JavaScript has an if statement, like Java and C++ do. The one difference is that the condition 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!");
}
}
You can add an else block to an if statement.
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. It is still good practice to always write the 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 braces.
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");
}
An if-else-if chain stops at the first condition that is true. If more than one condition would be true, only the block for the first one runs.
Ternary operator
Here is an 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;
}
Switch statement
When you need to compare a single value against many possibilities, you can use the switch statement instead of a long if-else-if chain:
const letter = "B";
let gpa;
switch (letter) {
case "A":
gpa = 4.0;
break;
case "B":
gpa = 3.0;
break;
case "C":
gpa = 2.0;
break;
case "D":
gpa = 1.0;
break;
case "F":
gpa = 0.0;
break;
default:
gpa = null;
}
console.log("Your GPA is " + gpa); // Your GPA is 3
- The
defaultcase in aswitchstatement is like the lastelsein anif-else-ifchain. It will be reached if none of the previously tested conditions aretrue. - The
breakstatement is needed to break out of theswitchstatement. If you omitbreak,switchwill run all the following cases until it encountersbreakor exits.
This fall-through behavior can be useful for grouping cases:
const day = "Saturday";
let type;
switch (day) {
case "Saturday":
case "Sunday":
type = "Weekend";
break;
default:
type = "Weekday";
}
console.log(type); // Weekend