!!(new Number(0)) == true, but !!(Number(0)) == false, why?
-
11-12-2019 - |
Question
Why do the last two behave differently (tested on Google Chrome's console)?
/* number */ /* string */
0 == false; '' == false;
!!0 == false; !!'' == false;
Number(0) == false; String('') == false;
!!Number(0) == false; !!String('') == false;
new Number(0) == false; new String('') == false;
(new Number(0)) == false; (new String('')) == false;
!!new Number(0) == true; !!new String('') == true;
In other words, why is casting to boolean different if Number
or String
are called with the new keyword (While e.g., Array()
and new Array()
work identically)?
Also, bonus question. Why is '' == 0
? I would expect that comparison to implicitly cast 0
to '0'
, since it would be a widening conversion, while casting both to booleans before the comparison is a narrowing conversion.
Solution
new Number(0)
returns aNumber
object, which is truthy regardless of its value. Therefore,!!(true) == true
.Number(0)
returns the number0
, which is falsey:!!(false) == false
As for your bonus question, ''
gets cast to an integer when you use the double equals sign. parseInt('') == 0
.
OTHER TIPS
new
gives you an object. Hence the comparison.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow