9

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}`));
zero298
  • 25,467
  • 10
  • 75
  • 100
  • If you can self answer it immediately after you ask it, it is not much of a question is it? It seems more like a documentation than a question. I am not sure if SO supports/allows that. – Sнаđошƒаӽ Aug 20 '18 at 18:36
  • 1
    @Sнаđошƒаӽ it could help others, though – Sacha Aug 20 '18 at 18:39
  • 2
    @Sнаđошƒаӽ [Can you answer your own questions on Stack Overflow?](https://meta.stackoverflow.com/questions/250204/can-you-answer-your-own-questions-on-stack-overflow) – Andreas Aug 20 '18 at 18:39
  • @Sacha [Can I answer my own question? - Help Center](https://stackoverflow.com/help/self-answer) – Andreas Aug 20 '18 at 18:40
  • @Andreas How did I miss that? I typed that exact title and still didn't see it. I could have sworn I sorted by relevance as well. – zero298 Aug 20 '18 at 18:45
  • 2
    Use google (or any other search provider) for searching. The built-in search isn't that good... :( – Andreas Aug 20 '18 at 18:46
  • And another question were SOs search system failed. I mean both this question and the dupe got ignore / destructuring / array / [javascript] in their title ... – Jonas Wilms Aug 20 '18 at 18:46

1 Answers1

18

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}`);
});
zero298
  • 25,467
  • 10
  • 75
  • 100