JavaScript Switch Statement
The JavaScript switch statement is another type of conditional statement used to control the flow of a program. It provides a simple and efficient way to execute different blocks of code based on the value of an expression. The switch statement is particularly useful when you have multiple conditions and you want to avoid using a large number of if...else
statements.
The syntax of the switch statement is as follows:
1switch (expression) { 2 case value1: 3 // code block 4 break; 5 case value2: 6 // code block 7 break; 8 default: 9 // code block 10}
In the above syntax, expression
is the value you want to test. The case
keyword is followed by the value you want to test against, and the code block that follows the case
value will be executed if the expression
matches the value. The break
keyword is used to exit the switch statement once a matching case is found. If none of the case
values match the expression, the code in the default
block will be executed.
Here is an example of how the switch statement can be used:
1let value = 2; 2switch (value) { 3 case 1: 4 console.log("Block 1"); 5 break; 6 case 2: 7 console.log("Block 2"); // output 8 break; 9 case 3: 10 console.log("Block 3"); 11 break; 12 default: 13 console.log("Not a valid day"); 14}
In this example, the value of value
is 2, so the code in the second case block will be executed, and "Block 2" will be logged to the console.
Without default in switch
1let value = 20; 2switch (value) { 3 case 1: 4 console.log("Block 1"); 5 break; 6 case 2: 7 console.log("Block 2"); 8 break; 9 case 3: 10 console.log("Block 3"); 11 break; 12}
Value of value
is 20 not matching any case statements, we wont get console log
With default in switch
1let value = 20; 2switch (value) { 3 case 1: 4 console.log("Block 1"); 5 break; 6 case 2: 7 console.log("Block 2"); 8 break; 9 case 3: 10 console.log("Block 3"); 11 break; 12 default: 13 console.log("Not a valid value"); 14}
Value of value
is 20 not matching any case statements, so it will execute the code inside default block.
Note: break statement is needed in all case block to avoid condition check for every case even though previous case statement is true.
JavaScript switch statement provides a simple and efficient way to control the flow of a program based on the value of an expression. By using switch statements, you can avoid writing long and complex if...else
statements, making your code more readable and maintainable.