JavaScriptSwitch declares that the condition declaration in JavaScript is used to complete behavior based on different conditions.
JavaScript Switch declaration
If you want to execute one of several code blocks, you can use the switch statement:
Syntax:
The code is as follows:
Switch (n)
{
Case 1:
Execution code block 1
Break
Case 2:
Execution code block 2
Break
Default:
If n is neither 1 nor 2, execute this code
}
Working principle: the (n) behind the switch can be an expression or (and usually) a variable. Then, the value in the expression is compared with the number in case. if it matches a case, the subsequent code is executed. Break is used to prevent the code from being automatically executed to the next line.
Instance:
<Script type = "text/javascript"> // You will receive a different greeting based // on what day it is. note that Sunday = 0, // Monday = 1, Tuesday = 2, etc. var d = new Date () theDay = d. getDay () switch (theDay) {case 5: document. write ("Finally Friday") break case 6: document. write ("Super Saturday") break case 0: document. write ("Sleepy Sunday") break default: document. write ("I'm looking forward to this weekend! ")} Script
[Ctrl + A Select All Note: If you need to introduce external Js, you need to refresh it to execute]