Self-Invoking Switch Functions
If you’ve been working with Javascript or Typescript for even a short time, you’ll know that one of the most common patterns when dealing with objects which can have multiple outputs is to create a let and then reassign the value with a statement.
For example, one of the most traditional (and messy) ways was to use chained if else statements;
const a = "a";
let MyVar;if (a === "a"){
MyVar = "a";
} else if (a === "b"){
MyVar = "b";
} else if (a === "c"){
MyVar = "c"
} else {
MyVar = "d"
}return MyVar;
The result of this will always be “a” since we’re checking what a const might be.
Another way of doing this could be with a switch statement;
const a = "a";
let MyVar;switch(a){
case "a":
MyVar = "a";
break;
case "b":
MyVar = "b";
break;
case "c":
MyVar = "c";
break;
default:
MyVar = "d";
break;
}return MyVar;
What if I was to tell you that there’s a much better way that doesn’t require you to mentally keep track of what a variable might be, and are cleaner to read? I call them self-invoking switch functions, and they look a little like this;
const a = "a";
const MyVar = (() => {
switch(a){
case "a":
return "a";
case "b":
return "b"
case "c":
return "c";
default:
return "d";
})()return MyVar;
What’s going on here?
Get Scott Pritchard’s stories in your inbox
Join Medium for free to get updates from this writer.
Quite simple really — You’re returning the output of a switch statement from inside a function. No need to break, and with a default value, you’re guaranteed to return something.
What’s more, if you don’t have a default, the result of this will be undefined! This is good — if you use something like this inside a function where the value of a field inside the object could possibly be undefined, you no longer return a key or a value!
Reverse it
There’s another cool trick that you can do with switch statements and functions, and that’s the reverse switch. Let’s say you have some complex logic where you need to check multiple conditions on each case, for example;
case a !== "a" && a !== "b"You might have several cases like this. We can use what is shown above to return a value based on complex logic;
const a = "a";
const MyVar = (() => {
switch(true){
case a !== "a" && a !== "b":
return "a";
case a !== "c" && a !== "d":
return "b";
default:
return "c";
})()return MyVar;
What we’re doing here is saying “For each case, check whether the result of that logic is true, and return this result if so”.
This is very handy if you’re creating an object and only want values which aren’t undefined.





