Skip to content

Instantly share code, notes, and snippets.

@jdfm
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdfm/71ad19574ce21ff85ae1 to your computer and use it in GitHub Desktop.
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...
// 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;
}
@jdfm
Copy link
Author

jdfm commented Jun 23, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment