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.
Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
What is null in JavaScript. JavaScript null is a primitive type that contains a special value null . JavaScript uses the null value to represent the intentional absence of any object value. If you find a variable or a function that returns null , it means that the expected object couldn't be created.
Null. In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With