Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the ‘Switch’ Statement?
2.1.
Syntax
3.
How does the switch statement work?
4.
Understanding the switch statement
5.
Frequently Asked Questions
6.
Key Takeaways   
Last Updated: Mar 27, 2024

JavaScript Switch Statement

Author Aryan Raj
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

JavaScript is a high-level, interpreted programming language used to make web pages more interactive. It is an object-based scripting language that supports polymorphism, encapsulation, and to some extent, inheritance as well. It doesn't have to be compiled like Java and C, which require a compiler as Javascript runs in a browser.

When we move further in the topic, we will find various properties, including the concept of Conditional statements. Conditional statements are executed depending upon different conditions that are true or false. 

Read More About, Basics of Javascript

Now, let's understand the switch statement in javascript.
 

What is the ‘Switch’ Statement?

The switch statement evaluates an expression, then compares its result with case values, and executes the statement associated with the matching case value.

It is used to execute different actions based on various conditions.

The JavaScript switch statement is used in decision-making.

Syntax

switch (expression) {
   case value1:
    // Statement 1;
    [break];

   case value2:
    // Statement 2;
    [break];

   case value3:
    // Statement 3;
    [break];

    default:
    //Statement;
}


How does the switch statement work?

  • The switch statement checks an expression inside parentheses ().
  • Compare the result with the value 1, Value 2, and so on.. in the case branches from top to bottom. The switch statement uses strict comparison (===).
  • Execute the statement in the case branch, where the result of the expression equals the value that follows the case keyword.
  • If the break statement is executed, the switch statement ends. The break statement is entirely optional. 
  • If the Break statement is not used, the cases after the matching case are also executed.
  • The default clause is also optional.
     

The switch statement evaluates an expression, compares its result with the case values, and then executes the statement associated with the matching case.

 

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Understanding the switch statement

Let us go through some examples which will help us understand more clearly about the switch statement in Javascript.

Example 1:

Switch statement to get the day of the week (JavaScript).
 

 var day = 5;
 let 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 ';
 }
 console.log(dayName); 


Output:

  Thursday

 

  • We have declared the day variable that holds the day number and the day name variable (dayName).
  • Using the switch statement, we can get the day of the week based on the day number. If the day is 1, the day of the week is Sunday. If the day is 2, the day of the week is Monday, and so on.
  • Output the day of the week to the console.


Example 2:

Switch statement With Multiple Case.
 

// multiple case switch program

 var fruit = 'apple';
 switch(fruit) {
    case 'apple':
    case 'mango':
    case 'pineapple':
    	console.log(`Fruit available on cart.`);
    break;
    default:
    	console.log(`This is not in our cart.`);
    break;
}

 

Output:

 Fruit available on cart

 

  • In the above code, multiple case statements are grouped.
  • All the grouped cases share the same code.
  • If the value of the fruit variable has the value mango or apple, the output will be the same.


Example 3:

What if we forget to write break?

 

 var age = 18;
 switch (age) {
    case 16:
    	console.log('Not allowed you are 16');
    break;
    case 18: 
    	console.log('Allowed your age is 18');
               // NOTE: the forgotten break would have been here
    case 19:  
    	console.log('Allowed your age is 19');
    break;  
    case 20:
    	console.log('You are 20');
    break;
    default:
    	console.log('default');
 }


Output:

  Allowed your age is 18
  Allowed your age is 19

 

  • Since Condition matches the case statement, age is 18; criteria are met here, so the block of code will be executed.
  • There is no break statement in 'case:18', so the next case will run.
  • After case:19, it encounters the break, so it will not continue into 'case:20'.
     

Check out this article - Balanced Parentheses

Frequently Asked Questions

Q1. Find the output of the code:

    var price = 6;
    switch (price) {
        case 2: console.log("It is: 2");
        default:console.log("It is: default");
        case 5: console.log("It is: 5");
        case 9: console.log("It is: 9");
    }
}

 

Ans:

It is: default
It is: 5
It is: 9

 

Q2. What are the drawback of a switch-case statement?

Ans: Disadvantages of switch statements are:

  1. We cannot use the float constant in the switch as well as in the case.
  2. We cannot use the variable expression in case.
  3. We cannot use the same constant in two different cases.
  4. We cannot use the relational expression in case.

 

Q3. Can you nest switch statements Javascript?

Ans: We can use a nested switch statement, but that can quickly become a spaghetti code, and therefore, it is not recommended. We can instead use functions with the nested switch statement for code clearance or use a recursive function depending on what the code is supposed to do.

 

Q4. Should switch statements always have a default clause?

Ans: No, it should usually contain a default clause. Involving a default clause only makes sense if there's something to do, such as asserting an error condition or providing a default behaviour.

Key Takeaways   

This article discussed the Switch statement in JavaScript with various examples. We also discussed in detail how ‘Switch’ works in Javascript.

If you are pursuing a new career in Web Development, we suggest you get your fundamentals crystal clear with our Full Stack Development course

Happy Learning, Ninja!

This course will help you!

Previous article
Loops in Javascript
Next article
JavaScript Throw Statement
Live masterclass