+ 12
Can anyone explain the switch statement in JavaScript?
9 Antworten
+ 3
simply switch statement is used to make different case's and uses in a proper way
+ 8
IT IS SIMILAR TO ELSE-IF STATEMENT.
IN SWITCH STATEMENT YOU ARE PASSING A VALUE AND SEE IF ANY CASE MATCHES THAT VALUE IF YES YOU EXECUTE THAT BLOCK AND BREAK OUT FROM SWITCH STATEMENT.
IF ANY CASE DOESNT MATCH WITH VALUE DEFAULT CASE IS EXECUTED WHICH IS SIMILAR TO ELSE IN ELSE-IF.
+ 5
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
code block
}
This is how it works:
The switch expression is evaluated once.The value of the expression is compared with the values of each case.If there is a match, the associated block of code is executed.
+ 5
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
The result of day will be:
Thursday
+ 4
when all the conditions are not matched then default is executed
+ 3
perfect explainations with examples, you can play quiz with right wrong with switch statment.
+ 2
switch statement is used in replace of multiple use of else if statement. case is used to to set different conditions, if there is a case that match the switch expression, it's then evaluated and break to stop execution. default is executed when all the case (s) are not matched
+ 1
Though one disadvantage of using switch is you can check only one variable.
Whereas through if else if different conditions can be provided.
I prefer using switch for most cases but some exceptions demand if else if