Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!