JavaScript Switch case statement; Through this tutorial, you will learn what is switch case statement and how to use the JavaScript switch case
statement to control complex conditional operations.
What is JavaScript switch case
statement?
The switch
case statement is a decision-making statement that is similar to the if else
statement.
You use the switch
case statement to test multiple conditions and execute a block of codes.
Syntax
Syntax of the switch
case statement:
switch (expression) {
case value_1:
statement_1;
break;
case value_2:
statement_2;
break;
case value_3:
statement_3;
break;
default:
default_statement;
}
Each case in the switch
statement expression is evaluated. The first case is tested against the expression. If the case matches the expression value the code executes and the break keyword ends the switch block.
In else condition, If the expression
does not match any value, the default_statement
will be executed. It behaves like the else
block in the if-else
statement.
Flowchart of switch
Case Statement
Example of JavaScript switch case
In the below example, declare two variables name first one is day and the second one is day name. Day variable represents the day of the week and day name represent day name.
<html> <head> <title>Switch Case Statments!!!</title> <script type="text/javascript"> var day = 4; var dayName; switch (day) { case 1: dayName = 'Sunday'; break; case 2: dayName = 'Monday'; break; case 3: dayName = 'Tuesday'; break; case 4: dayName = 'Wednesday'; break; case 5: dayName = 'Thursday'; break; case 6: dayName = 'Friday'; break; case 7: dayName = 'Saturday'; break; default: dayName = 'Invalid day'; } document.write("Day Name :- " + dayName); </script> </head> <body> </body> </html>