Understanding Switch Statements in JavaScript

Image from negativeย space

Whenever we are in situation of writing multiple if/else statement for a particular test case, then the multiple if/else statement can be replaced by switch statement.

Syntaxย :

switch(expression_or_value) {

case expression_or_value :
operation1
[break];
   case expression_or_value :
operation2
[break];
    ...  
   default : 
default operation
[break];

}
// break is optional

A switch statement first evaluates its input expression.

It then checks whether the first case expression evaluates to the same value as the result of the input expression, using strict equals (===).

If the case is matched then, the code associated with the case is executed until it finds the break keyword, or also the return keyword inside functions.

If the break or return is not added to the case, then the switch statement will continue and execute the code below the match. It will continue to run until it finds a break, return, or reaches the end of the statement.

If no matching case is found then the program looks for a default clause and executes the code there.

If a default clause is not found, then it reaches end of the switch expression and does nothing.

Example:

function getCost(item) {
  let cost ;
  switch(item) {
    case '๐ŸŒ':
cost = '10$';
break;

case '๐Ÿ‰' :
cost = '20$';

case '๐Ÿ“' :
cost = '30$';
break;

default :
cost = "Item not in stock";
  }
  return cost;
}

Letโ€™s execute the function and test it

getCost('๐ŸŒ'); // 10$
getCost('๐Ÿ‰'); // 30$
getCost('apple'); // Item not in stock

getCost(โ€˜๐ŸŒโ€™)โ†’ matches the first case and executes the cost = 10$ and executes the break statement, which ends the switch statement.

getCost(โ€˜๐Ÿ‰โ€™) โ†’ matches the second case and executes the cost = 20$. There is no break, so the code below it is executed, and the value of cost starts at 20$ but continues to run and becomes 30$ย .

getCost(โ€˜appleโ€™) โ†’ no matching case, so it executes the default case. For the last case, there is no need for the break statement because there will be no more case below itย .

Cases where we can skip break statement

If we want to execute same operation for two or more conditions, then we can make use of skipping break statement.

function isVowel(input) {
  let isVowel = false; 
  switch(input) {
    case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
isVowel = true;
  }
  return isVowel;
}

The order in which the cases are placed is not considered.

We can also place the default case anywhere inside the statement.

function getCost(item) {
  let cost = `The cost of ${item} is `;
  switch(item) {
    default :
cost = "Item not in stock";
break;
    case '๐ŸŒ';
cost = '10$';
break;

case '๐Ÿ‰' :
cost = '20$':

case '๐Ÿ“' :
cost = '30$';
break;
  }
return cost;
}

But donโ€™t forget to add a break statement to the end of default case if it is not placed at the end of all cases.

We can also add block to eachย case

function getMenu(option) {
    switch(option) {

case 'veg' : {
console.log('๐ŸŽ','๐Ÿ‰','๐ŸŒ','๐Ÿ“', '๐Ÿ');
break;
}

case 'non-veg': {
console.log('๐Ÿ—', '๐Ÿœ', '๐Ÿฅฉ','๐Ÿฃ');
break;
}

default :
console.log('๐Ÿ•','๐Ÿฅ“','๐Ÿฅ•','๐Ÿง');

}
  }

But when we need to use that?

In a switch expression, variables created inside any one of the case blocks is available to entire switch block.

function getMenu(option) {
    switch(option) {

case 'veg' :
let menu = ['๐ŸŽ','๐Ÿ‰','๐ŸŒ','๐Ÿ“', '๐Ÿ'];
console.log(...menu);
break;

case 'non-veg':
let menu = ['๐Ÿ—', '๐Ÿฅฉ','๐Ÿฃ']; // this will throw error
console.log(...menu);
break;

default :
console.log('๐Ÿ•','๐Ÿฅ“','๐Ÿฅ•','๐Ÿง');

}
  }

The above example throwsย , โ€œUncaught SyntaxError: Identifier โ€˜messageโ€™ has already been declaredโ€, which you were not probably expecting.

To solve this we can use a block {} for the case section.

function getMenu(option) {
    switch(option) {

case 'veg' : {
let menu = ['๐ŸŽ','๐Ÿ‰','๐ŸŒ','๐Ÿ“', '๐Ÿ'];
console.log(...menu);
break;
}
      case 'non-veg': {
let menu = ['๐Ÿ—', '๐Ÿฅฉ','๐Ÿฃ'];
console.log(...menu);
break;
}
      default : 
console.log('๐Ÿ•','๐Ÿฅ“','๐Ÿฅ•','๐Ÿง');
    }
}

We can have an expression for the switch andย case

switch(1+2) {

case 1:
console.log(1);
break;

case 1+2 :
console.log(3); // this will be executed
break;

}

The switch compares cases with strict equality

switch(1) {

case '1':
console.log(1);
break;

default :
console.log("Default"); // this will be executed

}

Thanks for Reading ๐Ÿ“–ย . Hope you like this if you found any typo or mistake send me a private note ๐Ÿ“ thanks ๐Ÿ™ ๐Ÿ˜Šย .

Follow me JavaScript Jeep๐Ÿš™๐Ÿ’จย .

Please make a donation here. 80% of your donation is donated to someone needs food ๐Ÿฅ˜. Thanks in advance.

Leave a comment

Design a site like this with WordPress.com
Get started