Home > OS >  Changing ternary expressions in js?
Changing ternary expressions in js?

Time:10-15

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 together ternary expressions together

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

Is this the suggested way to accomplish that?

CodePudding user response:

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

<!-- -->
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

are you talking about Expressions - 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 (?), 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"
  • Related