1

I have come accross this strange use if javascript array Can anyone explain me this.

[1,2,3][1,2]

What type of operation is this ?

Kpatel1989
  • 335
  • 3
  • 13

1 Answers1

3

In the expression

var result = [1, 2, 3][1, 2]

The first part [1, 2, 3] is an array literal, the second part [1, 2] is an index into the array. So it's equivalent to:

var array = [1, 2, 3];
var index = (1, 2);
var result = array[index];

(1, 2) is a comma expression. It evaluates its arguments from left to right, and returns the value of the last one, so it's equivalent to just 2. So the whole thing is equivalent to:

var result = array[2];

which sets result to 3.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Just to clarify, the comma expression would return the right-most element, ie `(1,2,3)` would return `3`. – Anthony Forloney Dec 23 '14 at 04:08
  • That's actually two comma expressions, equivalent to `((1, 2), 3)`, just as `1 + 2 + 3` is two addition expressions. – Barmar Dec 23 '14 at 04:10
  • Hi Barmar, I understood ur explanation for index. but i didnt get ((1,2),3). Please explain me the use of comma opeartor – Kpatel1989 Dec 23 '14 at 08:10
  • 1
    @Kpatel1989 These are binary operators, they take two arguments. If you used them multiple times in a row, they have to be grouped. So just as `1 + 2 + 3` is processed as `((1 + 2) + 3)`, `1, 2, 3` is processed as `((1, 2), 3)`. The value of `(1, 2)` is `2`, and `(2, 3)` is `3`, so `(1, 2, 3)` is `3`. – Barmar Dec 23 '14 at 08:13