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
[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 });
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With