jQuery Switch Statement

Sam Deering
Share

How to declare switch statements using JavaScript. Pretty handy to know it will save you lots of time when executing different code depending the value of variable.

var jsLang = 'jquery';
switch (jsLang) { 
	case 'jquery': 
		alert('jQuery Wins!');
		break;
	case 'prototype': 
		alert('prototype Wins!');
		break;
	case 'mootools': 
		alert('mootools Wins!');
		break;		
	case 'dojo': 
		alert('dojo Wins!');
		break;
	default:
		alert('Nobody Wins!');
}
//outputs "jQuery Wins!"

You can also fall through to match multiple cases by omitting the breaks like so:

var jsLang = 'prototype';
switch (jsLang) { 
	case 'jquery': 
		alert('jQuery sucks!');
		break;
	case 'prototype': 
		alert('prototype sucks!');
	case 'mootools': 
		alert('mootools sucks!');	
	case 'dojo': 
		alert('dojo sucks!');
		break;
	default:
		alert('Nobody sucks!');
}
//outputs "prototype sucks! mootools sucks! dojo sucks!"