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