Codectionary / Developer documentation / JavaScript

if...else and switch

if...else executes code blocks based on boolean conditions, with else if for additional conditions and a final else as a catch-all. switch compares a single value against multiple possible cases, useful when checking one variable against many discrete values - each case needs a break to prevent falling through to the next.

Syntax

if (condition) { } else if (condition) { } else { }
switch (value) { case x: break; default: }

Examples

if...else if...else

Handling multiple conditions in sequence.

function getGrade(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else {
    return "F";
  }
}

console.log(getGrade(85)); // "B"

switch Statement

Checking one value against several discrete cases.

function getDayName(day) {
  switch (day) {
    case 0:
      return "Sunday";
    case 1:
      return "Monday";
    case 2:
      return "Tuesday";
    default:
      return "Unknown";
  }
}

console.log(getDayName(1)); // "Monday"

// Fall-through: cases without break share the same code
function isWeekend(day) {
  switch (day) {
    case 0:
    case 6:
      return true;
    default:
      return false;
  }
}

Best practices

  • Use switch when comparing one value against many discrete options - it is more readable than a long if/else if chain in that case
  • Never forget the break statement in each switch case, or execution will fall through into the next case unintentionally
  • Always include a default case in a switch to handle unexpected values
  • For simple boolean conditions, prefer if/else or a ternary over switch

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation