JavaScript Switch Case Statement Tutorial

JavaScript Switch case statement; Through this tutorial, i am going to show you in detail about switch case statement and how to use the JavaScript switch case statement to control complex conditional operations.

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 of JavaScript Switch Case Statement

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>

Recommend JavaScript Tutorial

Leave a Comment