gopi1410
gopi1410

Reputation: 6625

behaviour of typeof in javascript

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

Answers (2)

Denys Séguret
Denys Séguret

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

Zeta
Zeta

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.

References:

Upvotes: 4

Related Questions