Skip to content

Instantly share code, notes, and snippets.

@rainabba
Created December 13, 2021 20:25
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 rainabba/ee2fb7d959582f90659bf81fa9579f97 to your computer and use it in GitHub Desktop.
Save rainabba/ee2fb7d959582f90659bf81fa9579f97 to your computer and use it in GitHub Desktop.
How to IIFE the switch statement and more

First, credit to the answer at https://stackoverflow.com/a/55944296/901899

Second, if you aren't comfortable with an IIFE (immediately executed function), you will want to check out https://www.tektutorialshub.com/javascript/immediately-invoked-function-expressions-iife/.

Now, because switch() {} is a "statement" in JavaScript and not a function, it can't be IIFE executed with the following

let failure = ( switch(x) { default: return true; } )(x);

You will get: "Uncaught SyntaxError: Unexpected token 'switch'"

This CAN be done using an "immediately-invoked lambda" (like IIFE, but lambda)

let success = ((x) => { switch(x) { default: return true; } })(x);

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