What is this notation in reduce()?

This function uses reduce to sum all numbers. I don’t understand what _ signifies as the second argument and what it does, I couldn’t find any documentation on this. Can someone please explain this code?

function test2(num) {
  return num === 0 ? 1
  : new Array(num).fill(undefined).reduce((acc, _, idx) => 
    acc + (idx + 1), 0)
}

This is just a way of naming an unused parameter

Ahh, that’s what I was starting to think, thank you

Umm so be careful with this because it’s ever-so-slightly a form of cargo cult programming

Some languages support this as a specific part of their syntax. Many do this primarily to make a feature called pattern matching easier to use (Haskell, OCaml, Erlang, Prolog, Rust would be examples). The language Go also supports it: in that case it’s because Go also supports multiple return syntax & commonly you are only interested in one of the return values. This is all fine and dandy.

The issue is that there is no special syntax in JS, it is literally just calling a variable/parameter _. So, particularly in the case of parameters, you cannot use it more than once. This is invalid syntax, for example: (_, _, index) => {.

With JS, I’m pretty certain it’s copied from functional programming langs, given they happen to be fashionable atm. I do it automatically, because the other language I use the most has it as syntax (as do two other languages I know, and it’s standard convention in the language I configure my text editor with), and I think it’s a bit of a bad habit.

Are you saying this is bad practice? But skipping the second argument entirely wouldn’t work in this case so a placeholder is needed, or at least that’s my understanding of it.

It works fine, but it’s a recent convention/habit, and the problem with it as a convention is this (admittedly relatively rare): say I have a function that takes three arguments and I’m only interested in the last one. I can’t do this:

(_, _, thisOne) => {
  doSomeThingWith(thisOne);
}

The syntax exists in other languages because they will literally ignore any underscore identifiers, they aren’t assigned as variables. In JS it’s literally just a normal identifier name, it’s naming a variable _, which isn’t the same thing at all.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.