4

In Mac Chrome JS console, I experience the following results:

{} evaluates to Object()

{}; evaluates to undefined

How does the semicolon affect what comes before it?

Is this related to ASI, or another rule of parsing?

michaeljsalo
  • 523
  • 4
  • 16
  • 1
    The Chrome console does what it does. It doesn't really mean anything. – Pointy Mar 09 '19 at 18:36
  • This is not a duplicate question. It may be related to another question and answer. https://stackoverflow.com/questions/36438034/why-is-no-longer-nan-in-chrome-console – michaeljsalo Mar 09 '19 at 18:53

2 Answers2

0

This is because JS interprets {} as an object literal, while {}; turns to a code block.
This can be avoided by putting that in a pair of parentheses: ({}); will return an object.

FZs
  • 16,581
  • 13
  • 41
  • 50
0

Chrome actually evaluates {} as if you've written ({}), thus forcing the interpreter to treat is as object literal as opposed to an empty block;

{ 
  console.log("the line starts with { so it's treated is an empty block, not an object");
}

({}) //this is an object that is discarded after the line is read

To illustrate that it's actually an empty block, see this code:

{} == {} //syntax error because the effective code is "== {}"

And compare with this code

({}) == {} //force the left side to be an object

In the above, the there is no error because it's evaluated correctly and then the result is dropped.

The following, however is a syntax error, so in that case Chrome silently drops the braces

({};)
VLAZ
  • 26,331
  • 9
  • 49
  • 67