Created
November 3, 2014 01:04
-
-
Save Elbone/2b2a53526f33b5a1b952 to your computer and use it in GitHub Desktop.
How to write switch statements the right way in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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