'Changing ternary expressions in JavaScript?

In Python I can do something like:

a = 1 if x==2 else 2 if x==3 else 3 if ... # Like a SQL CASE statement

Is there a similar way to do this in JavaScript? Currently I'm chaining ternary expressions together:

a = (x===2)? 1 : (x===3)? 2 : ...

Is this the suggested way to accomplish that?



Solution 1:[1]

Two alternatives come to mind.

switch/case statement

This doesn't exist in Python, but in JavaScript you can use a switch statement as follows:

const x = 3;
let a;


switch (x) {
  case 2:
    a = 1;
    break;
  case 3:
    a = 2;
    break;
  default:
    a = 1;
}

console.log(a);

<!-- -->

It's a little verbose, but you can get rid of some of the verbosity by wrapping it in a function:

function val(x) {
  switch (x) {
    case 2:
      return 3
    case 3:
      return 2;
    default:
      return 1;
  }
}

const x = 3;
const a = val(x);

console.log(a);

Lookup object

You can populate an object with lookup values. You can use a regular object, but since you're dealing with numeric keys, a Map is more suited:

const values = new Map([
  [2, 1],
  [3, 2]
]);

const x = 3;
const a = values.get(x);

console.log(a);

Solution 2:[2]

You may be talking about expressions - the conditional operator. Here is the example.

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), and then an expression to execute if the condition is truthy, followed by a colon (:), and finally the expression to execute if the condition is false. This operator is frequently used as a shortcut for the if statement.

function fun(var) {
  return (var ? '2' : '10');
}

console.log(fun(true));
// Expected output: "2"

console.log(fun(false));
// Expected output: "10"

console.log(fun(null));
// Expected output: "10"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robby Cornelissen
Solution 2 Peter Mortensen