DEV Community

Cover image for Inline switch statements in javascript?
Leonardo Montini
Leonardo Montini

Posted on

Inline switch statements in javascript?

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 ...
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

What do you think? Will you stick to the usual switch or will you give this a try? Let me know!

Top comments (4)

Collapse
 
besworks profile image
Besworks • Edited

You could accomplish this by wrapping your switch statement in an IIFE.

const result = (()=>{
  switch (key) {
    case 'foo' : return 4;
    default : return 1;
  }
})();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
balastrong profile image
Leonardo Montini

Sure, wrapping the switch inside a function is a good way and IIFE looks like a really smart and concise solution, thanks for sharing! :)

Collapse
 
alfiqmiq profile image
Marek

Try this:

(({ "key1": "val1", "key2": "val2"})[<key>] ?? "default value")
Enter fullscreen mode Exit fullscreen mode
let val = (({ "4": "case1", "8": "case2"})["4"] ?? "Unknown")

val => "case1"

let val = (({ "4": "case1", "8": "case2"})["123"] ?? "Unknown")

val => "Unknown"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jcalato profile image
MetalScreamer

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.