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

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

{} instanceof Object 

results in this error message:

Uncaught SyntaxError: Unexpected instance token

Can someone tell me why this is so and how to fix it?

+5
source share
4 answers

Grammar for instanceof:

 RelationalExpression instanceof ShiftExpression 

per ECMA-262 Β§11.8 .

The punctuator { at the beginning of the statement is considered the beginning of a block, so the next one } closes the block and terminates the statement.

The next instanceof statement is the beginning of the next statement, but it cannot be at the beginning because it must be preceded by RelationalExpression, so the analyzer gets a surprise.

You need to force {} be treated as an object literal, putting something else at the beginning of the statement, for example.

 ({}) instanceof Object 
+10
source

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

You need to change the context (for example, wrapping it in ( and ) ) to make it an object literal.

 ({}) instanceof Object; 
+3
source

If you try this:

 var a = {} a instanceof Object 

outputs true , which is the expected output.

However in your case

 {} instanceof Object 

The above does not output true.

The latter is not the same as the first. In the first case, we create an object literal, and in the second - not. Therefore, you get this error.

+1
source

Try

 var p = {} p instanceof Object 
+1
source

Source: https://habr.com/ru/post/1210975/


All Articles