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

222
Visualizações
How to get the first number in input values of range number or undefined

I want to get the first number value out of values with number or undefined range.

Obviously this fails for 0 which is falsy. What is the logical expression to return this?

    type Nomber = number | undefined

    function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
      return (a || b || c)
    }

    const test = (a: Nomber, b: Nomber, c: Nomber, expected: any) => {
      let got = a_or_b_or_c_number_value_including_zero(a, b, c)
      if (got !== expected) {
        console.log([a, b, c], 'fail', got, expected)
      }
    }


test(1, 2, 3, 1)
test(undefined, 1, 2, 1)
test(0, 1, 2, 0)
test(undefined, 0, 2, 0)
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use the nullish coalescing operator to check it.

According to MDN:

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.


This can be used in your code like below.

function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
  return (a ?? b ?? c); // Modified
}

This will make the code work the way you want, which will not make 0 equal to false.


This is how the code works.

Code Description
a ?? If a isn't null or undefined, use a.
b ?? c If b is null or undefined, use c, else, use b.

In conclusion, the nullish coalescing operator is a useful feature to not make 0 and "" equal to false (while || evaluates those values to false).

about 4 years ago · Juan Pablo Isaza Relatório

0

Use ?? instead of ||

function a_or_b_or_c_number_value_including_zero(a: Nomber, b: Nomber, c: Nomber) {
      return (a ?? b ?? c)
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the the Nullish coalescing operator (??) to workaround the 0 failing for being falsy.

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