Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is [1,2,3,4][1,2] in javascript [duplicate]

Tags:

javascript

can anyone explains the above question with explanation. I tried it console and the answer coming is 3

[1,2,3,4][1,2] //consoles 3
like image 482
Surendra Avatar asked Apr 27 '17 12:04

Surendra


2 Answers

[1,2,3,4] is an array literal.

1,2 is two numbers with a comma operator between them, so resolves to 2.

So you are getting index 2 (the third item) from the array.

var array = [1,2,3,4];
var property = (1,2);
var result = array[property];

console.log({ array: array, property: property, result: result });
like image 105
Quentin Avatar answered Oct 11 '22 13:10

Quentin


The first [1,2,3,4] is an array of 4 numbers.

The second [1,2] is a bracket notation (used here to access an item of the above array).

Inside that bracket notation you have a comma operator that evaluates to its right most expression 2.

So:

[1,2,3,4][1,2]

is the same as:

[1,2,3,4][2]

which is the same as:

var arr = [1,2,3,4];
arr[2];
like image 30
ibrahim mahrir Avatar answered Oct 11 '22 14:10

ibrahim mahrir