Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda