JavaScript: 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

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.)

Use break

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.

Add break if you want it to exit.

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc