282

I can't wrap my mind around this quirk.

[1,2,3,4,5,6][1,2,3]; // 4
[1,2,3,4,5,6][1,2]; // 3

I know [1,2,3] + [1,2] = "1,2,31,2", but I can't find what type or operation is being performed.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joe
  • 80,724
  • 18
  • 127
  • 145

3 Answers3

390
[1,2,3,4,5,6][1,2,3];
      ^         ^
      |         |
    array       + — array subscript access operation,
                    where index is `1,2,3`,
                    which is an expression that evaluates to `3`.

The second [...] cannot be an array, so it’s an array subscript operation. And the contents of a subscript operation are not a delimited list of operands, but a single expression.

Read more about the comma operator here.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 8
    correct.. last index used.. more examples: [1,2,3,4,5,6][1,2,3] === [1,2,3,4,5,6][3]; [1,1,1,5,1,1][3] === [1,1,1,5,1,1][1,2,3]; in this way [1,1,1,5,1,1][3] == 5 – mastak Sep 14 '11 at 18:24
110

Because (1,2) == 2. You've stumbled across the comma operator (or simpler explanation here).

Unless commas appear in a declaration list, parameter list, object or array literal, they act like any other binary operator. x, y evaluates x, then evaluates y and yields that as the result.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
21
[1,2,3,4,5,6][1,2,3];

Here the second box i.e. [1,2,3] becomes [3] i.e. the last item so the result will be 4 for example if you keep [1,2,3,4,5,6] in an array

var arr=[1,2,3,4,5,6];

arr[3]; // as [1,2,3] in the place of index is equal to [3]

similarly

*var arr2=[1,2,3,4,5,6];

 // arr[1,2] or arr[2] will give 3*

But when you place a + operator in between then the second square bracket is not for mentioning index. It is rather another array That's why you get

[1,2,3] + [1,2] = 1,2,31,2

i.e.

var arr_1=[1,2,3];

var arr_2=[1,2];

arr_1 + arr_2; // i.e.  1,2,31,2

Basically in the first case it is used as index of array and in the second case it is itself an array.

PengOne
  • 48,188
  • 17
  • 130
  • 149
Imdad
  • 5,942
  • 4
  • 33
  • 53