Why "typeof + ''" returns 'number'?
javascript
Solution
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
For reference:
- Whats the significant use of Unary Plus and Minus operators? (SO)
- ES5 #9.3.1 ToNumber Applied to the String Type (ES5 Spec)
- Operator Precedence (MDN)
Problem
Let's try to type code below in console: ``` typeof + '' ``` This returns 'number', while typeof itself without argument throws an error. Why?