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.

Was it helpful?

Solution

  • new Number(0) returns a Number object, which is truthy regardless of its value. Therefore, !!(true) == true.
  • Number(0) returns the number 0, 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
scroll top