While this method is functional
const a = [1, 2, 3];
const index = 2;
const [,,v1] = a;
// v1 = 3
const { [index]: v2 } = a;
// v2 = 3
The use of the second solution (v2
) is considered poor design practice as arrays and objects differ in structure.
A more optimal approach would be either of these:
const v3 = a[index];
const v4 = a?.[index];
In essence, destructuring is most effective when the data structure is known. If uncertain, JavaScript arrays do not raise errors for out-of-bounds accesses but non-array values require optional chaining (e.g. v4
).
Edit 2022
To justify why the second method is deemed a "bad design practice," consider running this benchmark:
// ran 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
Mere functionality does not equate to efficiency or good design. While I could use a pipe wrench to hammer a nail, there are undoubtedly better tools at hand.
Edit 2024
Upon the previous update, Array.at witnessed increased adoption.
const v5 = a.at(index);
This technique is favored due to its distinction from object property access.
For instance:
const i = 1;
const p = 'find';
// old
const v6 = a[i]; // 2
const v7 = a[p]; // 'find() [native code]' (same as a.find)
// new
const v8 = a.at(i); // 2
const v9 = a.at(p); // 1 (similar to a.at(0)
This updated API guards against retrieving unintended values via unwanted property accesses.
Bonus: a.at(-2)
corresponds with a[a.length - 2]