Switch Statement in Javascript

Switch Case

Switch statements can be used in place of multiple if statements where only 1 condition is checked. The advantage of switch is that, the statement directly jumps to the correct case skipping all other saving you a few nano seconds. But the disadvantage is, you cannot check for multiple condtions. Also, its easier for a person to read it.


switch (expression) {
  case value1:
	Statement;
	break;
  case value2:
  	Statement;
	break;
  case valueN:
  	Statement;
	break;
  default:
  	Statement;	
  	break;
}

The expression is tested against the case values and if it is true then the case statements are executed.

The break keyword is used to break the case and hence come out of the switch.

In case no value matches the expression, then the default case is executed.

What happens if you forgot to add break at the end? Try and comment in the section below.


var month = 4;
switch(month){
	case 1:
		month = 'January';
		break;
	case 2:
		month = 'February';
		break;
	case 3:
		month = 'March';
		break;
	case 4:
		month = 'April';
		break;
	case 5:
		month = 'May';
		break;
	....
	....
	case 12:
		month = 'December';
		break;
	default:
		console.log("Please enter a valid month");
}

Why is break not used in default?

Common Case

Sometimes you may need to execute same set of statements for 2 or more cases. Will you copy the code twice or thrice, well its not a good practice to repeat the code multiple times. For that, switch provides us to add cases one after the other to run same statements.

var marks = 8;
switch(marks){
	case 1:
	case 2:
	case 3:
		console.log("Poor");
		break;
	case 4:
	case 5:
	case 6:
		console.log("Good");
		break;
	case 7:
	case 8:
	case 9:
		console.log("Very Good");
		break;
	case 10:
		console.log("Excellent");
		break;
	default:
		console.log("Please Enter marks");
}


Next > < Prev
Scroll to Top