What does "_" mean in this code?

Tell us what’s happening:
Describe your issue in detail here.
I am trying to understand what “" means in solution 4 of “Factorialize a Number”. I understand the other solutions in “Factorialize a Number”, but I’m trying to understand “tail recursion”. So what does "” mean? I found the underscore library. Is that what “_” refers to in this code?

  **Your code so far**
  return num < 0 ? 1 :
    new Array(num)
      .fill(undefined)
      .reduce((product, _, index) => product * (index + 1), 1);
}
factorialize(5);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36

Challenge: Factorialize a Number

Link to the challenge:

The “underscore library” refers to lodash, I believe - which isn’t what is being used here.

An underscore used in a function’s parameters indicates a parameter that isn’t going to be used in the function’s code. In this case, the reduce method’s callback accepts up to 4 values, but the code isn’t using the second value so replaces the parameter with the underscore.

It’s basically a “workaround” for function parameter/argument order.

In the example code, the currentValue isn’t used but the code still needs access to the index and you can’t just do (previousValue, currentIndex) as that would make the currentIndex the currentValue. The order has to be (previousValue, currentValue, currentIndex).

So if you do not need the current value you can do (previousValue, _, currentIndex).

1 Like

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