this question has answer here:
- why [5,6,8,7][1,2] = 8 in javascript? 4 answers
i accidentally typed:
var x = [1, 2, 3, 4]; console.log(x[1, 2]); //this log 3 console.log(x[3, 1]); //this log 2
it turns out can use number of comma-separated indices refer array elements. last index used. if last index larger array, undefined
result.
why syntax work?
because contents of property access brackets expression. in case expression series of operands , comma operators, evaluates final operand (2
, 1
, respectively, in examples). array index that'll accessed.
this fundamentally same using other operators in expressions in property access brackets dynamically evaluate property name accessed, e.g. x[x.length - 1]
or x[some_var * 3]
.