Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "typeof + ''" returns 'number'?

Tags:

javascript

Let's try to type code below in console:

typeof + ''

This returns 'number', while typeof itself without argument throws an error. Why?

like image 645
accme Avatar asked Feb 22 '13 23:02

accme


2 Answers

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)
like image 68
Fabrício Matté Avatar answered Nov 08 '22 16:11

Fabrício Matté


That evaluates to typeof(+''), not (typeof) + ('')

like image 1
Eric Avatar answered Nov 08 '22 16:11

Eric