JavaScript
Article

jQuery Switch Statement

By Sam Deering

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

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.