DEV Community

Discussion on: Arrow functions: a walkthrough and gotchas

iroachie profile image
Kyle Roach

_ as a variable is used when you want to ignore the first parameter when using a function, we sometimes call it a throwaway variable.

A great example in the Array.forEach method. Say we wanted to loop through items in an array and console out the index.

The first argument in the forEach callback is the item, and the second is the index. Because parameters are ordered in js, if we want to use the 2nd one, we have to provide a variable for the 1st one.

const names = ['Sylwia', 'Kyle'];

names.forEach((name, index) => console.log(index))

Since what we really need is the second variable, we can omit the first one with _.

names.forEach((_, index) => console.log(index))

So _ acknowledges there is a parameter there, but we're not using it in our implementation.

Here are two posts I found you can use for reading:

Thread Thread
sylwiavargas profile image
Sylwia Vargas Author • Edited

Awesome! Thanks. This is what I meant by

there will for sure be no defaults you care about

I was aware of the Wes Bos' post, which is where I encountered the _ back in the day. Since this is niche, produces warnings and seems to be treated differently by dev teams, I am quite curious about how the argument came to be and what the intention was behind it — perhaps the ES6 standards or discussion thread will shed some more answer.

Thanks for the research — I've included a mention of your comment in the blog :)