JavaScript Switch Case Statement Tutorial

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

 switch case statement flowchart

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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *