3

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
brk
  • 48,835
  • 10
  • 56
  • 78

1 Answers1

4

Breakdown of [1,2,3,4][1,2]

  1. [1,2,3,4]: A normal array of four elements
  2. 1,2: Comma operator returning the last operand. Thus, giving result as 2
  3. 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
Tushar
  • 85,780
  • 21
  • 159
  • 179