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"
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"
Share
Improve this question
asked Mar 29, 2013 at 10:30
gopi1410gopi1410
6,62510 gold badges43 silver badges76 bronze badges
2 Answers
Reset to default 6typeof 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.
+"..."
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.
References:
typeof
operator- Unary
+
operator