Nodejs switch case

Nodejs switch case :

Switch Case in NodeJS, first evaluates the expression provided in brackets after switch keyword, then based on the result of expression, the cases below it are compared.
When any of the below cases are matched, then the code present in that case is executed.

Syntax of Javascript Switch Case :


switch(expression) {
case one:
// code block to be executed if the result of expression is one
break;
case two:
// code block to be executed if the result of expression is two
break;
default:
// code block to be executed if none of the above case is matched.
}

Use of break keyword :

If you are providing the break keyword, then the code execution will stop and it will come out of the switch case.
This means it will not check for other cases, present in the switch block.

It is better to provide the break statement after the case is matched and desired code is executed, as it will
save the compute time further.

Example of switch case in NodeJs/Javascript

 
const month = 1

switch (month) {

  case 1:
    console.log("January Month");
    break;

  case 2:
    console.log("February Month");
    break;

  case 3:
    console.log("March Month");
    break;

  case 4:
    console.log("April Month");
    break;

  case 5:
    console.log("May Month");
    break;

  case 6:
    console.log("June Month");
    break;

  case 7:
    console.log("July Month");
    break;

  case 8:
    console.log("August Month");
    break;

  case 9:
    console.log("September  Month");
    break;

  case 10:
    console.log("October Month");
    break;

  case 11:
    console.log("November Month");
    break;

  case 12:
    console.log("December Month");
    break;

  default:
    console.log("No Month selected");
    break;

}

OutPut :

"January Month"

 

Question : What will happen if we are not providing the break statement in the switch case?

Answer : If we are not providing the break statement the code will further execute all consecutive case statements
until it finds next break statement or till the end of switch case block.
If it does not find the break statement till the default block, the default block will also gets executed.

Example :

 
const cond = 'Two';
switch (cond) {
case 'One':
console.log('In case One block');
break;

case 'Two':
console.log('In case Two block');

case 'Three':
console.log('In case Three block');

default:
console.log('In default block');
}

OutPut :

  
"In case Two block"
 "In case Three block"
 "In default block"