Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda