Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using object notation as if it were an array - why does this evaluate?

Tags:

javascript

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?

like image 408
Joe Shanahan Avatar asked Dec 14 '16 15:12

Joe Shanahan


People also ask

Why is it better to use objects instead of arrays?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

Why do we use array of objects?

Advantages of Array of Objects: The array of objects represent storing multiple objects in a single name. In an array of objects, the data can be accessed randomly by using the index number. Reduce the time and memory by storing the data in a single variable.

How do you check if an object is an array or not?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

What is the difference between accessing an object with dot vs with [] in JavaScript?

The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.


1 Answers

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.

like image 71
Niet the Dark Absol Avatar answered Oct 25 '22 23:10

Niet the Dark Absol