2

I can do:

{test : 10}

But how is this valid JS and why do I get 7 when I add this to the chrome js console?

{test: 10, 7}

How is this trailing 7 valid if it doesn't have a key?

Is this a special JS object literal syntax? Where can I read more about it and why it evaluated to 7?

When I do: const test = {test: 10, 7}; // VM140:1 Uncaught SyntaxError: Unexpected token '}'

That gives me a expected error so how come without assigning it to a variable it is valid JS and the console returns to me the value 7?

When I do:

{test: 10, 7, 8}

I then get 8

I also get an error if I try JSON notation:

{'test': 10, 7}

Whats going on here?

BlackStar
  • 21
  • 1
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Robin Zigmond Feb 25 '21 at 21:13
  • 1
    Does this answer your question? [What does a comma do in JavaScript expressions?](https://stackoverflow.com/questions/3561043/what-does-a-comma-do-in-javascript-expressions) – Robin Zigmond Feb 25 '21 at 21:16
  • confusing thing is Block VS Object and how the code is seen based on the content. You have a label https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label inside of a block – epascarello Feb 25 '21 at 21:39

2 Answers2

1

The object isn’t relevant; the not very useful comma operator returns the last value.

console.log( (10, 7) ) // 7

We need extra parentheses here so that it’s not interpreted as a second argument to 'console.log`, but the same thing is happening.

Ben West
  • 3,665
  • 1
  • 12
  • 15
1

There are 2 things happening here, but the key thing is that this is not a JavaScript object literal. As you've seen, const test = {test: 10, 7} fails.

Firstly, {let foo=7;} is valid code; the braces are being used as block scope, not object notation.

Secondly, test: statement is being used to label a statement, not as a key in an object.

So your code is the same as:

{
    test:
    (10, 7)
}
cmbuckley
  • 33,879
  • 7
  • 69
  • 86