I realize that this is improper syntax, but why is JavaScript ignoring the first number and giving a response instead of breaking?
let myArray = [1,2,3,4]
myArray[0,1] // 2
myArray[1,3] // 4
myArray[3,0] // 1
I realize that this is improper syntax, but why is JavaScript ignoring the first number and giving a response instead of breaking?
let myArray = [1,2,3,4]
myArray[0,1] // 2
myArray[1,3] // 4
myArray[3,0] // 1
It's not improper syntax.
From docs:
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
For instance, [1,2][1,2]
, perhaps bizarrely enough, will return undefined
.
Why?
The second [
is interpreted by the compiler to be the array subscript operator, because JavaScript's semantics don't allow two arrays to be next to each other.
Thus, the second 1,2
must be an expression that evaluates to an index. 1,2
results in the first operand being evaluated, followed by the second, which is what's returned. So it uses index 2
, which of course doesn't exist in that array, and we get undefined
.
This is because it is evaluating the comma operator in each set of square brackets.