May 06, 2021 JavaScript
Switch statements are used to perform different actions based on different conditions.
Use the switch statement to select one of the more than one block of code to execute. You can learn how to use switch statements for multi-option selection in JavaScript programming.
Code interpretation:
How it works: First set the
expression n
(usually a variable). T
he value of the expression is then compared to the value of each case in the structure. I
f there is a match, the block of code associated with the case is executed.
Use
break
prevent code from automatically running to the next case.
Show the name of today's week. Please note that Sunday is 0, Monday is 1, Tuesday is 2, and so on:
The result of x's operation:
If JavaScript encounters
break
keyword, it jumps out of the switch block.
This will stop the execution of more code in the block as well as
case
If a match is found and the task is completed, execution is interrupted at random. No more testing is required.
break
saves a lot of execution time because it "ignores" the execution of other code in the switch block.
You don't have to interrupt the last case in the switch
case
The block of code ends naturally here.
Use the default keyword to specify what to do if the match does not exist:
If today is not Saturday or Sunday, the default message is output:
The result of x's operation:
The default case does not have to be the last case in the switch block:
switch (new Date().getDay()) {
default:
TEXT = "Looking forward to weekends!"
break;
case 6:
TEXT = "Today is Saturday";
break;
case 0:
TEXT = "Today is Sunday";
}
If default is not the last case in the switch block, remember to end the default case with break.
Sometimes you need a different case to use the same code.
In this example, case 4 and 5 share the same block of code, while 0 and 6 share another block of code:
switch (new Date().getDay()) {
case 4:
case 5:
Text = "Weekend is coming :)"
break;
case 0:
case 6:
TEXT = "Today is weekend ~";
break;
default:
TEXT = "Looking forward to weekends!"
}
If multiple casees match a case value, select the first case.
If no matching case is found, the program continues to use the default label.
If the default label is not found, the program continues with the statement after switch.
Switch case uses a strict comparison.
The value must be the same as the type you want to match.
Strict comparisons can only be true if the operans belong to the same type.
In this example, x will not match:
var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
Easy to learn JavaScript: JavaScript Switch Case