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.

var 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"); // prints 「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.

var y = (4 > 5) ? "yes" : "no";

console.log(y); // prints "no"

Switch Statement

// example of switch statement.
var x = "a"; // change the value to test

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 ≈ 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.
var x = "w";

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

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Tutorial by Example
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth