Switch. Consider a variable—its value may be 10, 20 or 30. We can test this in a switch statement, and this may offer optimal performance.
Switch considerations. JavaScript now is a compiled language. Is it worth using a switch statement (on integers) instead of a series of if-else tests?
First example. It is good to start with a simple example. Here we see a switch statement inside a function called testValue. We pass an integer to testValue.
And The switch statement determines what value to return based on the argument.
Note If no cases match, the switch is exited. We then reach the "return 0" so the value zero is returned.
function testValue(value) {
"use strict";
// Switch on the argument to return a number.switch (value) {
case 0:
return -1;
case 1:
return 100;
case 2:
return 200;
}
return 0;
}
// Call testValue.
console.log("SWITCH RESULT: " + testValue(0))
console.log("SWITCH RESULT: " + testValue(2))SWITCH RESULT: -1
SWITCH RESULT: 200
Default. A case matches just one value—an integer or string. But the default case matches all other values. It is an "else" clause in the switch.
var number = 5;
// Use a default case in this switch.switch (number) {
case 4:
console.log("FOUR");
break;
default:
console.log("NOT FOUR");
}NOT FOUR
Last break statement. In JavaScript the last break statement is not required. The last case statement will execute without a break and no errors will occur.
Note Fall through occurs when no break is present, but for the last case (often "default") this will not change behavior.
Note 2 In a brief test, I found that Google Chrome has no performance change if you omit the last break statement.
function test(value) {
// No break statement is required on the last case.switch (value) {
case 0:
console.log("ZERO");
break;
case 1:
console.log("ONE");
break;
case 2:
console.log("TWO");
}
}
test(0);
test(1);
test(2);ZERO
ONE
TWO
Lookup tables. An object can be used instead of a switch statement to look up anonymous functions. We then call those functions. This appears to be slower than a switch statement.
A summary. With switch statements in JavaScript, we have a way to test a variable and run code based on its value. This can make code more elegant and symmetrical.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.