5

Let's try to type code below in console:

typeof + ''

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

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
accme
  • 373
  • 1
  • 2
  • 11
  • 2
    Because of the unary plus. – Dave Newton Feb 22 '13 at 23:24
  • http://stackoverflow.com/questions/9081880/what-is-unary-used-for-in-javascript – Cybrix Feb 22 '13 at 23:25
  • The reason why `+` is not interpreted as addition or concatenation operator is because `typeof` itself is a unary operator, not a function: http://es5.github.com/#x11.4.3. Treating `+` as unary plus is the only way to make this expression valid. – Felix Kling Feb 22 '13 at 23:31

3 Answers3

7

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:

Community
  • 1
  • 1
Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159
1

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

Eric
  • 87,154
  • 48
  • 211
  • 332
1

Javascript interprets the following + '' as 0 so :

typeof + '' will echo `number'

To answer your second question, typeof takes an argument so if you call it by itself it will throw an error same thing if you call if by itself.

Mehdi Karamosly
  • 4,996
  • 1
  • 25
  • 46