Control Flow

Switch Case in JavaScript

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed.


Syntax
switch(variable) { 
    case valueOne: 
        //statements 
        break; 
    case valueTwo: 
        //statements
        break; 
    default: //optional
    //statements
}

Notes

A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.


Example
var choice = 'Y';
switch(choice) { 
    case 'Y' : 
        console.log("Yes"); 
        break; 
    case 'M' : 
        console.log("Maybe"); 
        break; 
    case 'N' : 
        console.log("No"); 
        break; 
    default: 
        console.log("Invalid response"); 
}

See Also
Documentation

switch - JavaScript | MDN

Add to Slack

< If Statement   |   Ternary Operator >

© 2019 SyntaxDB. All Rights Reserved.