Last active
August 29, 2015 14:23
-
-
Save jdfm/71ad19574ce21ff85ae1 to your computer and use it in GitHub Desktop.
It's possible to use a switch block as an alternative to if else if else, but with a few caveats...
This file contains 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
// classic example | |
if ( somevalue === 1 ) { | |
// do the thing | |
} else if ( somevalue === 2 ) { | |
// do some other thing | |
} | |
switch ( somevalue ) { | |
case 1: /* do some thing */ break; | |
case 2: /* do some other thing */ break; | |
default: break; | |
} | |
// alternative example | |
switch ( true ) { | |
case somevalue === 1: /* do some thing */ break; | |
case somevalue === 2: /* do some other thing */ break; | |
default: break; | |
} | |
// more interesting example | |
function checkValue( value, expected ){ return value === expected; } | |
switch ( true ) { | |
case checkValue( somevalue, 1 ): /* do some thing */ break; | |
case checkValue( somevalue, 2 ): /* do some other thing */ break; | |
default: break; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you use the second variant, you need to make sure your expressions are actually returning boolean values. Given that you can use some more complex expressions it's possible to use the guard and default operations in the case expressions it could be returning a falsey/truthy value instead of false/true.