JS: Branch Control: if then else, switch

By Xah Lee. Date: . Last updated: .

If Then Else

Simple “if” statement.

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");}

Curly brackets {} is optional if there's just one statement, but semicolon is still required.

if (3 > 4) console.log("yes");
else console.log("no");
// no

“if then else” Expression

JavaScript also supports “if then else” EXPRESSION. (aka “ternary expression”)

test ? expr1 : expr2 → if test 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 uses === for comparison. (The === operator does not do automatic type conversion.)

JavaScript Switch is Like Goto

JavaScript's “switch” 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.

// JavaScript's “switch” jumps to a point and continue from there.
const x = "w";

switch(x) {
    case "w":
        x += "1";
    case 32:
        x += "2";
    default:
        x += "3";
}
console.log(x); // w123

JavaScript Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog