This article translates the JavaScript Tutorial playlist of up master Kudvenkat on YouTube
SOURCE Address here:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
When should we use the Swtich statement
To enhance readability, we can replace the IF-ELSE-IF statement with a switch statement
Notice that the following code has multiple IF-ELSE-IF statements
var userinput = number (Prompt ("Please enter a number", "")); if (Userinput = = 1) { alert ("You are One");} Else if (Userinput = = 2) { alert ("You are number is");} Else if (Userinput = = 3) { alert ("Your number is three");} Else { alert ("Your number is not between 1 and 3");}
The above code can be written with a switch statement to greatly increase readability
Switch(userinput) { Case1: Alert ("Your number is one"); Break; Case2: Alert ("You are number is"); Break; Case3: Alert ("You are three"); Break; default: Alert ("You are not between 1 and 3"); Break;}
In general, you need to add a break after each case to jump out of the Swtich statement
So what happens if you don't add break in the switch statement?
Then the next case will run automatically after the case is found, until the entire program is run
In the following example, we no longer add a break statement in the CASE1, then when we enter the number 1, we get two alerts, the first alerts from Case1, and the second alert from Case2.
varUserinput = number (Prompt ("Please enter a number", "" "));Switch(userinput) { Case1: Alert ("Your number is one"); Case2: Alert ("You are number is"); Break; Case3: Alert ("You are three"); Break; default: Alert ("You are not between 1 and 3"); Break;}
But should you merge multiple case statements together?
If you want to give more than one case to the same code, you can combine the following together. A case statement if there are no statements in it, then there are multiple different values to share a box. A case without code automatically jumps to the next
In this case, the CASE1 and Case2 will automatically jump to CASE3 and run the code
var userinput = number (Prompt ("Please enter a number", "")); Switch (userinput) { Case 1: case 2: case 3 : alert ("You are number is" + userinput) ; Break ; default : alert ("You are not between 1 and 3"); Break ;}
Translation The switch statement in JavaScript