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!"
Sam Deering Sam Deering
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

  • 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! ;)

Related books & courses
Available now on SitePoint Premium

Preview for $1