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

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

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

0

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

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

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