jQuery Switch Statement

Sam Deering
Tweet

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!"

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Greg

    wait a second here mister ->>
    alert(‘jQuery sucks!’);
    o.0
    (j/k)

    • http://jquery4u.com/ jQuery4u

      Someone forgot to take their pills this morning eh Greg! ;)