I declared two variables player1 and player2.
const player1 = {undefined};
const player2 = {null};
player1 returns {undefined:undefined} but player2 returns null Why? what is the reason behind it?
I declared two variables player1 and player2.
const player1 = {undefined};
const player2 = {null};
player1 returns {undefined:undefined} but player2 returns null Why? what is the reason behind it?
There are a few things going on here with {null}
:
const player2 = {null};
is a syntax error. The right hand side is evaluated as an object literal with shorthand property name, and a shorthand name must be an IdentifierReference (see ECMAScript specs on Object Literal). But null
is a reserved word and is thus not valid as identifier reference.
{null}
on its own -- where it is not part of a larger expression -- is interpreted as a statement block, and is valid. Imagine it as:
{
null;
}
A console (like Chrome's dev console) may first try to parse an input like {undefined}
or {null}
as object literal. This works for {undefined}
because it is valid syntax for an object literal (undefined
is not a reserved word). When this is not possible (in the case of {null}
) it may interpret it as a statement block.
When the console evaluates a statement (block) it may echo the value of the last evaluated expression. Thus the console may respond to {null}
with null
, just like it would respond to {null; 1}
with 1. I suppose it was this behaviour that lead to the question.
If we would not use shorthand property names, then the syntax rules no longer require an IdentifierReference, but accept an IdentifierName, and those can be reserved words.
So these object literals are OK:
const n = {null: null};
const t = {this: this};
const f = {false: false};
But these are syntax errors:
const n = {null};
const t = {this};
const f = {false};
While these are valid again, but as statement blocks:
{null}
{this}
{false}