sdgfsdh
sdgfsdh

Reputation: 37095

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?

Upvotes: 4

Views: 79

Answers (4)

Francesco
Francesco

Reputation: 1413

When it is not too long I like to use || and && for this purpose.

const foo = (x === 1 && 'bar') || (x === 2 && 'goo') || 'zoo'

Upvotes: 0

deceze
deceze

Reputation: 522382

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';

Upvotes: 4

Dylan Meeus
Dylan Meeus

Reputation: 5802

TL;DR: There is no such expression

The ternary is possible

The way you have done is with the ternary would be the correct approach in this case. But as you could see, it indeed does not scale well.

But using a function seems better

A fix would be to use a function that returns you a value.

  function getSomething(input)
  {
     if(input == 1)
         // return for case 1
     if(input == 2)
         // return for case 2
      ...
  }

Upvotes: 3

Xorandnotor
Xorandnotor

Reputation: 156

No. The logically equivalent expression would be either a nested ternary operator, as you've listed, or a similarly unwieldy construct of boolean operands.

Upvotes: 0

Related Questions