Javascript switch


The JavaScript switch allows you to select multiple possible results for a scalar (expression).

switch (expr) {
    case result1:
       // statement1
    break;
    case result2:
       // statement2
    break;
    ……
    default:
       // statement
}

Grammatical explanation

The system evaluates the value of expr and chooses the corresponding statement according to the result (result1, result2, etc.). If all of the case results do not match, the statement in default will be executed.

break use for get out of the process, although the syntax can be omitted, but should not omit, otherwise it will continue to execute the following code, even if the equation does not match with the case of expr case (this is the difference with if else).

var x = 2;
switch (x) {
    case 0:
      alert("x more than 0");
    break;
    case 1:
      alert("x less than 1");
    break;
    case 2:
      alert("x equal 2");
    break;
    default:
      alert("x not equal to 1, 2 and 0");
    break;
}

Result

x equal 2



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook