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 default case in a switch statement is like the last else in an if-else-if chain. It will be reached if none of the previously tested conditions are true.
  • The break statement is needed to break out of the switch statement. If you omit break, switch will run all the following cases until it encounters break or 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