The switch Statement

The syntax for the switch statement in JavaScript:


switch (expression) { 
    case value: statement 
        break; 
    case value: statement 
        break; 
    case value: statement 
        break; 
    case value: statement 
        break; 
    default: statement 
}

The following code:


if (i == 2){ 
    document.writeln("2"); 
} else if (i == 3) { 
    document.writeln("3"); 
} else if (i == 4) { 
    document.writeln("4"); 
} else { 
    document.writeln("Other"); 
}

can be rewritten as follows:


switch (i) { 
    case 2: 
        document.writeln("2"); 
        break;
    case 3: 
        document.writeln("3"); 
        break;
    case 4: 
        document.writeln("4"); 
        break;
    default: 
        document.writeln("Other"); 
}

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

A fall-through case statement:


switch (i) { 
    case 2: 
    case 3: /* falls through */
        document.writeln("2 or 3"); 
        break;
    case 4: 
        document.writeln("4"); 
        break;
    default: 
        document.writeln("Other"); 
}

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


switch ("hello world") {
    case "hello" + " world": 
        document.writeln("hello"); 
        break;
    case "goodbye": 
        document.writeln("see you"); 
        break;
    default: 
        document.writeln("Unexpected message was found."); 
}

Case expressions with comparison operators:

 
var num = 2; 
switch (true) { 
    case num < 0: 
        document.writeln("Less than 0."); 
        break; 
    case num >= 0 && num <= 10: 
        document.writeln("Between 0 and 10."); 
        break; 
    case num > 10 && num <= 20: 
        document.writeln("Between 10 and 20."); 
        break; 
    default: 
        document.writeln("More than 20."); 
}
  

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

Home 
  JavaScript Book 
    Language Basics  

Statements:
  1. The if Statement
  2. The do...while Statement
  3. The while Statement
  4. The for Statement
  5. The for-in Statement
  6. Labeled Statements
  7. The break and continue Statements
  8. The with Statement
  9. The switch Statement