Home
Map
switch StatementSelect a case in the switch statement and compare the switch to an if-else block.
Node.js
This page was last reviewed on Dec 13, 2023.
Switch. 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.
Switch considerations. When we use switch, we have a symmetrical construct that acts on possible values. This can make the code more elegant.
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) { // 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.
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.
function Lookup Table
Summary. 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.
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.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.