Jan Prichystal
Jan Prichystal

Reputation: 136

How come {}"123" is a valid expression in Javascript REPL?

I was trying something in the Chrome (and FF) console and realized that the JS REPL evaluates some expressions in a surprising way:

{} "123" 
-> "123"


{} 123 
-> 123

{} [] 
-> []

Etc.

Why is that? Also, somewhat inconsistent with the previous behavior:

{}{} 
-> undefined

What's the logic behind the fact that these are valid expression?

Upvotes: 3

Views: 78

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

  1. Semicolons are optional in Javascript. So:

{} "123" is the same as {}; "123"; which yield the value of the last expression ("123").

  1. {} could be both an object literal or a block.

If {} is not implicitly taken as an object literal (no assignment or no key value pairs ...) then the interpreter will parse it as a block.

{}{} is the same as:

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

yielding undefined which is the value of an empty block.

Upvotes: 9

Related Questions