Skip to content

Instantly share code, notes, and snippets.

@Elbone
Created November 3, 2014 01:04
Show Gist options
  • Save Elbone/2b2a53526f33b5a1b952 to your computer and use it in GitHub Desktop.
Save Elbone/2b2a53526f33b5a1b952 to your computer and use it in GitHub Desktop.
How to write switch statements the right way in js
// NOT SWITCHES
function doSomething(condition) {
switch (condition) {
case 'one':
return 'one';
break;
case 'two':
return 'two';
break;
case 'three':
return 'three';
break;
default:
return 'default';
break;
}
}
// BUT USE LOOKUPS
function doSomething (condition) {
var stuff = {
'one': function () {
return 'one';
},
'two': function () {
return 'two';
},
'three': function () {
return 'three';
}
};
if (typeof stuff[condition] !== 'function') {
return 'default';
}
return stuff[condition]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment