Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the JavaScript array operation [1,2,3,4][1,2] return 3? [duplicate]

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]
like image 800
brk Avatar asked Apr 13 '26 16:04

brk


1 Answers

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
like image 152
2 revsTushar Avatar answered Apr 16 '26 04:04

2 revsTushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!