Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token instanceof (with Chrome Javascript console)

I am surprised that the following code when input into the Chrome js console:

{} instanceof Object

results in this error message:

Uncaught SyntaxError: Unexpected token instanceof

Can anyone please tell me why that is and how to fix it?

like image 415
balteo Avatar asked Jan 13 '15 11:01

balteo


2 Answers

The grammar for instanceof is:

RelationalExpression instanceof ShiftExpression

per ECMA-262 §11.8.

The punctuator { at the start of a statement is seen as the start of a block, so the following } closes the block and ends the statement.

The following instanceof operator is the start of the next statement, but it can't be at the start because it must be preceded by a RelationalExpression, so the parser gets a surprise.

You need to force {} to be seen as an object literal by putting something else at the start of the statement, e.g.

({}) instanceof Object
like image 124
RobG Avatar answered Sep 28 '22 01:09

RobG


{}, in that context, is a block, not an object literal.

You need change the context (e.g. by wrapping it in ( and )) to make it an object literal.

({}) instanceof Object;
like image 32
Quentin Avatar answered Sep 28 '22 00:09

Quentin