Let's try to type code below in console:
typeof + ''
This returns 'number', while typeof itself without argument throws an error. Why?
The unary plus operator invokes the internal ToNumber
algorithm on the string. +'' === 0
typeof + ''
// The `typeof` operator has the same operator precedence than the unary plus operator,
// but these are evaluated from right to left so your expression is interpreted as:
typeof (+ '')
// which evaluates to:
typeof 0
"number"
Differently from parseInt
, the internal ToNumber
algorithm invoked by the +
operator evaluates empty strings (as well as white-space only strings) to Number 0
. Scrolling down a bit from the ToNumber
spec:
A StringNumericLiteral that is empty or contains only white space is converted to
+0
.
Here's a quick check on the console:
>>> +''
<<< 0
>>> +' '
<<< 0
>>> +'\t\r\n'
<<< 0
//parseInt with any of the strings above will return NaN
That evaluates to typeof(+'')
, not (typeof) + ('')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With