3

I accidentally typed:

var x = [1, 2, 3, 4];
console.log(x[1, 2]); //this will log 3
console.log(x[3, 1]); //this will log 2

It turns out I can use any number of comma-separated indices to refer to array elements. The last index is always used. If the last index is larger than the array, undefined is the result.

Why does this syntax work?

Jay
  • 3,471
  • 4
  • 35
  • 49
  • 11
    The syntax isn't doing what you think its doing. Review the documentation of the comma operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – wrshawn Apr 27 '15 at 21:47
  • @EricJ. I think the upvoted comment from user1403582 answers the question pretty well actually. Maybe I framed it wrong; I wasn't looking for the spec-writer's intentions. – Jay Apr 27 '15 at 21:48
  • why didn't you read the spec or documentation before asking this question here? – Ejaz Apr 27 '15 at 21:50
  • 1
    @Ejay Because the point of having a Q&A site like this is to not have to read the entire spec to find out one thing. Having said that, I accept my question is a duplicate. Not easy to find though, unless you know what you're looking for. – Jay Apr 27 '15 at 21:50
  • Really, does Q&A sites defy purpose of having a list of operators and their purposes (or documentation for a language)? – Ejaz Apr 27 '15 at 21:51
  • 1
    I never thought of the comma as an operator. What would I have looked for? Obviously you're way smarter than me, because you already knew that. I think that most newbs would be turned off our community if told brusquely to RTFM. They (like me here) might not know what to ask. There can be a balance between good, well-researched questions and brushing people off. The balance here was that the question has already been answered elsewhere on the site. – Jay Apr 27 '15 at 21:59

1 Answers1

4

Because the contents of property access brackets is an expression. In this case the expression is a series of operands and comma operators, which evaluates to the final operand (2 and 1, respectively, in your examples). That is the array index that'll be accessed.

This is fundamentally the same as using other operators in expressions in property access brackets to dynamically evaluate the property name that will be accessed, e.g. x[x.length - 1] or x[some_var * 3].

JMM
  • 26,019
  • 3
  • 50
  • 55