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

152
Vistas
Trying to simplify this JavaScript expression dealing with undefined

I want to preserve the undefined if pinned is actually undefined, otherwise, I want to set the value across the equals sign to 1 if pinned is true and 0 if it's false. I came up with this that works, but I keep looking at it and it seems like it should be simpler.

const resultingValue = pinned === undefined ? undefined : pinned ? 1 : 0;

What I'm wanting is:

if pinned is undefined, return undefined if pinned is true, return 1 if pinned is false, return 0 otherwise, return 0;

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could check type and return either a number of boolean or undefined.

const
    resultingValue = typeof pinned === 'boolean'
        ? +pinned
        : undefined;
about 4 years ago · Juan Pablo Isaza Denunciar

0

Works for: true, false, undefined, 0, 1

const resultingValue = +pinned + 1 ? +pinned: undefined;
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a lookup table for each value. The undefined can be omitted since it is going to produce undefined by default:

const lookup = {true: 1, false: 0};
const convert = value => 
  lookup[value];

console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());

This can be shortened to a single function, if desired:

const convert = value => 
  ({true: 1, false: 0}[value]);

console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());

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