In some languages like C#
we have the possiblity of returning values from a switch
statement or in functional like Scala
we have pattern matching that is even better, making it more readable in case our goal is to return a value (even after some computation).
Javascript does not have such a function, natively.
Not a life changer, but I think it would be cool to be able to do something like
const result = switch(key) { case 'foo': 4 ...
A cool usage is in React when you're in need of a switch inside your JSX code.
Let's recap the advantages of such a thing:
- No need to reassign a variable
- Can use immutability with a const - safer code
- Can be easily used in JSX
- Can support validation in case there are duplicated cases
- No longer have bugs because you forgot to reassign, return or add break at the end
Mostly for fun, I created a little library to do so, you can already find it on https://www.npmjs.com/package/iswitch
Just run npm install iswitch
in your project and you're good to go!
Some examples:
const myKey = 'foo';
// Single case
const result = iswitch(myKey, ['foo', () => 1], ['bar', () => 8]); // 1
// Multiple case
const result = iswitch(myKey, [['foo', 'bar'], () => 1]); // 1
// Default
const result = iswitch(myKey, [['bar'], () => 1], [[], () => 5]); // 5
What do you think? Will you stick to the usual switch or will you give this a try? Let me know!
Top comments (4)
You could accomplish this by wrapping your switch statement in an IIFE.
Sure, wrapping the switch inside a function is a good way and IIFE looks like a really smart and concise solution, thanks for sharing! :)
Try this:
This is awful, hardr to read than just assigning a variable. I do like the soution proposed by the other commenter. Using IIFE definitely makes this more readable. In reality it's about time that JS actually implemented a version of this built into the language.