How to switch statement in Javascript

Description

The syntax for the switch statement in JavaScript:


switch (expression) { 
    case value: statement 
        break; //  ww  w . j  a  v a 2  s  .  c om
    case value: statement 
        break; 
    case value: statement 
        break; 
    case value: statement 
        break; 
    default: statement 
}

The following code:


if (i == 2){ /*from www  .  j  a v a2s.c  om*/
    console.log("2"); 
} else if (i == 3) { 
    console.log("3"); 
} else if (i == 4) { 
    console.log("4"); 
} else { 
    console.log("Other"); 
}

can be rewritten as follows:


switch (i) { //from www .ja  v  a2  s .co m
    case 2: 
        console.log("2"); 
        break;
    case 3: 
        console.log("3"); 
        break;
    case 4: 
        console.log("4"); 
        break;
    default: 
        console.log("Other"); 
}

Putting a break statement after each case avoids having cases fall through into the next one.

A fall-through case statement:


switch (i) { //  w w w. java2s . c  o m
    case 2: 
    case 3: /* falls through */
        console.log("2 or 3"); 
        break;
    case 4: 
        console.log("4"); 
        break;
    default: 
        console.log("Other"); 
}

The switch statement works with all data types and the case values need not be constants.


switch ("hello world") {
    case "hello" + " world": 
        console.log("hello"); 
        break;/*w  ww  .  jav  a  2s . c  o  m*/
    case "goodbye": 
        console.log("see you"); 
        break;
    default: 
        console.log("Unexpected message was found."); 
}

Example

Case expressions with comparison operators:


var num = 2; /*w  w w  .  ja  va 2s  .  com*/
switch (true) { 
    case num < 0: 
        console.log("Less than 0."); 
        break; 
    case num >= 0 && num <= 10: 
        console.log("Between 0 and 10."); 
        break; 
    case num > 10 && num <= 20: 
        console.log("Between 10 and 20."); 
        break; 
    default: 
        console.log("More than 20."); 
}

The switch statement compares values using the identically equal operator, therefore "10" is not equal to 10.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions