Why does typeof + '' 'return' number '?

Try entering the code below in the console:

typeof + '' 

This returns 'number', and typeof without an argument causes an error. Why?

+4
source share
3 answers

The unary plus operator calls the internal ToNumber algorithm in a 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" 

Unlike parseInt , the internal ToNumber algorithm, called by the + operator, evaluates empty lines (as well as white space-only lines) to Number 0 . ToNumber bit from ToNumber spec :

A StringNumericLiteral that is empty or contains only a space is converted to +0 .

Here is a quick check on the console:

 >>> +'' <<< 0 >>> +' ' <<< 0 >>> +'\t\r\n' <<< 0 //parseInt with any of the strings above will return NaN 

For reference:

+6
source

This is the value of typeof(+'') , not (typeof) + ('')

+1
source

Javascript interprets the following + '' as 0 like this:

typeof + '' will echo `number '

To answer your second question, typeof takes an argument, so if you call it on its own, it will throw an error if you call if .

+1
source

All Articles