Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have an expression form of switch?

When getting a value conditionally, I like to use the ternary operator (?:) so that I can have const variable declarations:

// Better
const foo = x ? 'bar' : 'goo';

// Worse
var foo;
if (x) {
    foo = 'bar';
} else {
    foo = 'goo';
}

I would like to do the same for switch statements. I can use a series of nested ?:, but this is quite cumbersome and does not scale well:

const foo = x === 1 ? 'bar' : (x === 2 ? 'goo' : 'zoo');

I could even use a closure, but this is also verbose:

const foo = (() => {
  switch(x) {
    case 1: 
        return 'bar';
    case 2: 
        return 'goo';
    default:
        return 'zoo';
  }
})();

Is there a switch expression in JavaScript?

like image 840
sdgfsdh Avatar asked Mar 11 '23 11:03

sdgfsdh


1 Answers

You should first and foremost keep things readable and manageable. Squeezing two or three conditions with four or five values into one line is unreadable almost any way you turn it.

I'd suggest this very declarative approach:

let fooToBarMap = {
    foo: 'bar',
    baz: 42
};

let y = fooToBarMap[x] || 'default';
like image 105
deceze Avatar answered Mar 21 '23 09:03

deceze