Reputation: 6625
Can someone explain why typeof behaves in the following way:
typeof
//Returns: SyntaxError: Unexpected token } (Quite obvious)
"Why am I a " + typeof
//Returns: SyntaxError: Unexpected token }
"Why am I a " + typeof + "";
//Returns: "Why am I a number"
"Why am I a " + typeof + "??";
//Returns: "Why am I a number"
Upvotes: 2
Views: 3481
Reputation: 382150
typeof isn't a function but a unary operator, so
typeof + "";
is the same as
typeof (+ "");
and +something
converts the something
to a number as is precised in EcmaScript norm on the unary + operator :
The unary + operator converts its operand to Number type.
Upvotes: 6
Reputation: 105886
+"..."
will actually parse the string as a number. This will result in typeof + ""
returning "number", even though the returned number is NaN
.
The first two usages are simply wrong, since typeof
needs a right hand side.
Upvotes: 4