I'm self-answering this because I didn't come across a question or answer that discussed ignoring a destructured array element while searching.
Is there a way to ignore an element of a array when destructuring? The closest thing that I can think of is how in Go you can use the _
symbol to drop an argument.
I'm using ESLint and I'd like to be able to avoid unused variable warnings without having to explicitly turn off the warning. I also don't like the scope leak even though it is rather minimal.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// I don't actually want 'a' to be available in the scope
arr.forEach(([a, b]) => console.log(`a: ${a} | b: ${b}`));
// _ is still defined and equates to 'a' above
arr.forEach(([_, b]) => console.log(`'a': ${_} | b: ${b}`));
No, destructuring will give you a reference. AFAIK, there is no way to configure a destructure to shallow clone at the same time.
Nested Array Destructuring You can also do nested destructuring with arrays. The corresponding item must be an array in order to use a nested destructuring array literal to assign items in it to local variables.
It looks like destructuring feature works by reference and it's not copying the value. So when you work with destructuring bear in mind to pay a lot of attention when you change a value inside your destructured Objects and Arrays!
You can ignore an element by simply not providing a variable for the value to be assigned to and just putting the comma as though you had. See MDN: Destructuring assignment#Ignoring some returned values.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// Just use ','
arr.forEach(([, b]) => {
// No variable is populated with the first element
console.log(typeof(a));
console.log(typeof(b));
console.log(`b: ${b}`);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With