I am not able to understand why this JavaScript array is returning 3. What is the logic behind returning 3?
I just executed this in a developer's tool:
[1,2,3,4][1,2]
I am not able to understand why this JavaScript array is returning 3. What is the logic behind returning 3?
I just executed this in a developer's tool:
[1,2,3,4][1,2]
Breakdown of [1,2,3,4][1,2]
[1,2,3,4]
: A normal array of four elements1,2
: Comma operator returning the last operand. Thus, giving result as 2
arr[2]
: Accessing the element from array using Bracket Notation/Property Accessor.Thus the resulting equivalent statement will be [1, 2, 3, 4][2]
.
This is equivalent to
var index = 1, 2; // Note the comma operator. This is same as `var index = 2;`
var arr = [1, 2, 3, 4];
arr[index]; // arr[2] = 3