Consider a variable in a Node.js program. We can test the variable's value in a switch
statement—this may be a cleaner and faster way to perform the test.
When we use switch
, we have a symmetrical construct that acts on possible values. This can make the code more elegant.
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
.
switch
statement determines what value to return based on the argument.switch
is exited. We then reach the "return 0" so the value zero is returned.function testValue(value) { // 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
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
break
statementIn JavaScript the last break
statement is not required. The last case statement will execute without a break
and no errors will occur.
break
is present, but for the last case (often "default") this will not change behavior.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
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.
With switch
statements in Node.js, we have a way to test a variable and run code based on its value. This can make code more elegant and symmetrical.