While this works
const a = [1, 2, 3];
const index = 2;
const [,,v1] = a;
// v1 = 3
const { [index]: v2 } = a;
// v2 = 3
The second solution (v2
) is a bad design practice, because an array is not an object, but you are accessing it as one.
A better solution would be either
const v3 = a[index];
const v4 = a?.[index];
In other words, destructuring is when you know the format of the data structure. If not, JavaScript arrays don't care if you try to get an out-of-bound value, unless the value is not an array, in which case you need optional chaining (e.g. v4
).
Edit
To clarify what I meant by the second solution being a "bad design practice", consider this benchmark:
// tested on Chrome 105 Firefox 105
let value = list[index]; // fastest, base fastest, base
let value = list?.[index]; // 2.52% slower 3.74% slower
let { [index]: value } = list; // 47.72% slower 30.76% slower
It's not because a feature exist, and it works, that 1) it's efficient or 2) it's a good design choice. After all, I can certainly hit a nail with a pipe wrench, but there are better tools for the job.