Why does [5,6,8,7][1,2] = 8 in JavaScript?

Asked by At

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.

4 Answers

Lightness Races in Orbit On Best Solutions
      ^         ^
      |         |
    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.

Mike Samuel On

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.

Imdad On

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]


*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


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.

Peak Sornpaisarn On

The second array is a pointer to the first array. It will get value for each item in the first array. For example:

var arr=["a","b","c","d","e"][1,2,3]

lets call firstArray = ["a","b","c","d","e"] the second array will first point b because firstArray[1] = "b". Then the second pointer will point at c because of firstArray[2] = "c". Then the last pointer will point at d because of firstArray[3] = "d". Therefore, it takes the final value, which is "d". You can look at it this way:

var firstArray=["a","b","c","d"] 
var arr = firstArray[1,2,3] 
console.log(arr) //this will be equal to "d" 

Or if you change your sequence like this

var firstArray=["a","b","c","d"] 
var arr = firstArray[1,2,0]
console.log(arr) //this will be equal to "a"