Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 843
Jan Prichystal Avatar asked Mar 16 '26 08:03

Jan Prichystal


1 Answers

  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.

like image 80
ibrahim mahrir Avatar answered Mar 18 '26 20:03

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!