9

I don't understand why the following evaluates to 3 instead of just declaring a syntax error when ran from a JavaScript REPL or through Chrome's Developer Tools:

{1, 2, 3};
3

As far as I can see, that should be a syntax error as demonstrated with:

var foo = {1, 2, 3};
Uncaught SyntaxError: Unexpected token ,

I feel like there's just some quirky behaviour I'm not aware of?

1
  • 1
    "I feel like there's just some quirky behaviour I'm not aware of?" -> that's proof of actual understanding of Javascript ! Commented Dec 14, 2016 at 15:24

1 Answer 1

12

Here's the breakdown of the symbols:

  • { Start code block
  • 1 Number literal
  • , Comma operator (evaluates both sides, returns right side)
  • 2 Number literal
  • , Comma operator
  • 3 Number literal
  • } End code block

Code blocks aren't restricted to defining if, while etc. blocks, they can be used anywhere. Therefore, your code is simply a block that contains a chained comma operator sequence, which returns the last item in the chain, hence 3.

In the case of var foo = {1, 2, 3};, the { is indeed a "start object literal" symbol and not a "start code block" symbol.

The same symbol can have multiple meanings based on context.

Sign up to request clarification or add additional context in comments.

1 Comment

It hit me when I got to your first bullet point, thanks :) Will accept once SO deems the correct amount of time has passed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.