JavaScript: Branch Control: if then else, switch

By Xah Lee. Date: . Last updated: .

If Statement

Simple if-statement syntax:

if (testExpr) {body}

if (3 < 4) {
  console.log("yes");
  console.log("and yes");
}
if (3 < 4) {
  // something
  console.log("yes");
}

If-Else Statement

if (3 <= 4) {
  // something
  console.log("yes");
} else {
  // something
  console.log("no");
}

Else-If Chain

const x = 3;
if (x == 1) {
  // something
  console.log("is 1");
} else if (x == 2) {
  // something
  console.log("is 2");
} else if (x == 3) {
  // something
  console.log("is 3");
} else {
  // something
  console.log("not found");
}

If-Then-Else Expression

testExpr ? expr1 : expr2
if testExpr eval to true, then return expression expr1, else return expr2.
console.log(((4 > 5) ? "yes" : "no") === "no");

Switch Statement

πŸ›‘ WARNING: switch-statement does fall-through. It'll jump to a matching point and run all of the rest of case branches without testing. Think of JavaScript switch as goto. Add break if you want it to exit.

πŸ’‘ TIP: switch is not useful. It is not a replacement for if-else chain, because it only compares a value, you cannot give it a general true/false expression.

// example of switch statement

const x = "a";

switch (x) {
  case "w":
    console.log("is w");
    break; // without break, it'll continue to run rest case branches without testing
  case "a":
    console.log("is a");
    break;
  case 3:
    console.log("is 3");
    break;
  default:
    console.log("none of the above");
}
BUY Ξ£JS JavaScript in Depth