Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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"
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!