Inline switch statements in javascript?
Leonardo Montini
Posted on July 15, 2022
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!
Posted on July 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 27, 2022