0

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?

  • 4
    The second line is a syntax error. The first works because `undefined` is a symbol, essentially a variable name, so the `{ undefined }` expression is valid. – Pointy May 03 '23 at 18:01
  • Does this answer your question? [null vs. undefined and their behaviour in JavaScript](https://stackoverflow.com/questions/7000762/null-vs-undefined-and-their-behaviour-in-javascript) – Filburt May 03 '23 at 18:01
  • @Filburt, I don't see how that other Q&A answers the question at hand. – trincot May 03 '23 at 18:12
  • How are these "returning" those results? When I try to run just this code (appending `console.log` statements to observe the results), I get a syntax error. Can you provide a runnable [mcve] which demonstrates what you are observing? – David May 03 '23 at 18:14
  • 1
    @Amodh your comment is unhelpful. JavaScript is one of the most heavily used languages on the planet. – Pointy May 03 '23 at 19:17
  • @trincot I think it provides the understanding of undefined vs. null that is obviously missing. – Filburt May 03 '23 at 21:39
  • @Filburt, that Q&A doesn't touch on anything that explains the behaviour mentioned in this question. – trincot May 04 '23 at 06:05

1 Answers1

3

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}
trincot
  • 317,000
  • 35
  • 244
  • 286