Why is {} "123" a valid expression in the Javascript REPL?

I tried something in the Chrome (and FF) console and realized that the JS REPL evaluates some expressions in an amazing way:

{} "123" 
-> "123"


{} 123 
-> 123

{} [] 
-> []

      

Etc.

Why? Also, somewhat inconsistent with the previous behavior:

{}{} 
-> undefined

      

What is the logic behind this being a valid expression?

+3


source to share


1 answer


  • Semicolons are optional in Javascript. So:

{} "123"

matches {}; "123";

, which gives the value of the last expression ( "123"

).

  1. {}

    can be either an object literal or a block.

If {}

implicitly accepted as an object literal (no assignment or key pair), the interpreter will parse it as a block.



{}{}

matches:

{
  // block with no expressions
};
{
  // block with no expressions
};

      

gives undefined

which is the value of the empty block.

+9


source







All Articles