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
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
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];
[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 });
It's an immediately invoked array with a comma operator
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
for the index.
[1, 2, 3, 4][1, 2]
resolves to
[1, 2, 3, 4][2] // 3