JavaScript: Branch Control: if then else, switch

By Xah Lee. Date: . Last updated: .

If Statement

Simple “if” statement syntax:

if (testExpr) {body}

The curly brackets {} are optional when there is only one statement or expression in body.

If testExpr is true, run body, else do nothing.

The testExpr is forced into one of true or false by Boolean Constructor.

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

If-Else Statement

if (3 <= 4) console.log("yes");
else console.log("no");

“else if” chain.

const x = 3;
if (x == 1) console.log("is 1");
else if (x == 2) console.log("is 2");
else if (x == 3) console.log("is 3");
else 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

// example of switch statement

const x = "a";

switch (x) {
  case "w":
    console.log("is w");
    break; // without “break”, it'll continue to run rest without testing
  case "a":
    console.log("is a");
    break;
  case 3:
    console.log("is 3");
    break;
  default:
    console.log("none of the above");
}

Switch-statement uses the Triple Equal Operator to test equality.

Tip: JavaScript Switch-Statement is Goto

JavaScript's switch-statement does fall-through. It'll jump to a matching point and run all of the rest of case code without testing. Think of JavaScript switch as goto.

Add break if you want it to exit.

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc