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

172
Visualizações
JavaScript Arithmetic's

I am wondering this code, trying to understand the nan or Nan value since it is not falsy or truthy and it's just a Number object of the type of number, the question is here why does this return zero since Nan is not falsy

my expected value here is Nan

    tip = '.'
    total = 10
    let totalPlusTip = ((total * (tip/100)) + total) || 0
    console.log(totalPlusTip) //0

my expected value here is 110

    tip = 10
    total = 100
    let totalPlusTip = ((total * (tip/100)) + total) || 0
    console.log(totalPlusTip) //110

since Nan is not false why isn't returning Nan when we do

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The reason why the first code output 0 is because NaN is false and in || operator, the Logical OR operator || returns the value of its second operand, if the first one is false.

You could see below, the value of ((total * (tip/100)) + total) is NaN and !NaN return true which means is return false. Since NaN is false, || return the second value which is 0.

  let tip = '.'
   let total = 10
    let totalPlusTip = ((total * (tip/100)) + total) || 0
  console.log(total * (tip/100))
  console.log(!NaN)
    console.log(totalPlusTip) //0

about 4 years ago · Juan Pablo Isaza Relatório

0

Unfortunately, It's falsy.

However, you can use Nullish coalescing operator (??) if you don't care about IE.

let totalPlusTip = ((total * (tip/100)) + total) ?? 0

Only null or undefined will be 0.

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