Is there a way in which I can destructure an array in the parameters of its prototype functions?
For example, I can use an Array.prototype function such as forEach to evaluate the value of each array element and log an individual sub-array value using bracket notation:
const array = [[0,1],[3,4],[5,6]];
array.forEach(element => console.log(element[0]));
// -> 0
// -> 3
// -> 5
If I want to refer to a sub-array element by an assigned name, can I do so with destructuring? Currently, I know I can do it like this:
let array = [[0,1],[3,4],[5,6]];
array.forEach(element => {
let first = element[0];
let second = element[1];
console.log(first);
// -> 0
// -> 3
// -> 5
});
What I would like to achieve using destructuring is assigning these variable names the way you normally would with destructuring in a typical function's parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach([first, second] => console.log(first));
// Uncaught SyntaxError: Malformed arrow function parameter list
Is this possible?
After a little bit of trial and error, it appears this is fully possible. You just have to wrap the restructuring parameter in parentheses the same way you would if there were multiple parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach(([first, second]) => console.log(first));
// -> 0
// -> 3
// -> 5