Why does `{} == null` give a SyntaxError? [duplicate]

∥☆過路亽.° 提交于 2021-02-17 21:29:35

问题


I can compare {} to true or false or itself, but comparison to null or undefined gives a syntax error. Is this because {} is an object value and not a reference? It feels weird that it would be a Syntax Error instead of some kind of runtime type error, or just work.

To clarify, I'm curious why this is a SyntaxError, mostly compared to doing {} == {} which is not only not a SyntaxError, but no error at all.


回答1:


There are two main contexts when parsing code: the expression context and the statement context. The body of a function for example is a statement context, the right side of an assignment is an expression context. To distinguish both makes sense to forbid things like:

 if( if(true) ) alert("nonsense");

Now REPL have a really difficult task: On the one hand, they have to parse functions and codeblocks that get entered, and on the other hand you sometimes just want to check how a certain object look like. Therefore this:

 { a: 1, b: 2 }

is actually a SyntaxError in JavaScript, as a { in a statement context starts a block of code, and : is invalid then. However the REPL is clever enough and puts that object into an expression context, and evaluates it as if it would be in parens:

({ a: 1, b: 2 })

the same happens for:

 {} == {}

which is actually also a SyntaxError, however the REPL also moves it into an expression context:

 ({} == {})

That "moving into an expression context" is a complicated task, and it seems as if the REPL just does not see the expression here:

 {} == null

and therefore parses {} as a block. Thats the case because the REPL just naively checks if the first and the last character are { and }, which is the case for {} == {} but not for {} == null.

Relevant part of the chromium sourcecode:

 if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
  text = '(' + text + ')';

executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);


来源:https://stackoverflow.com/questions/53306680/why-does-null-give-a-syntaxerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!