React: Map function with two parameters

Viewed 1052

I'm following a React tutorial that creates a clickable 5 star rating system, and am stuck on what seems like a basic Javascript point. In the anonymous map function below, why is the n necessary?

When I try removing the n, the app begins returning "NaN out of 5 stars" instead of a real number. But why is this? The n seemingly isn't even used in the function at all.

{createArray(totalStars).map((n, i) => (
        <Star
          key={i}
          selected={selectedStars > i}
          onSelect={() => setSelectedStars(i + 1)}
        />
      ))}

Thank you!!

2 Answers

Because that's how map() works, its 1st argument is always the currentVaule and the second one is index. You can't reach index without stating currentVaule or index will take its place.

function callback( currentValue[, index[, array]])

If you ommit n then i eventually becomes the first paramter. This is basic JS related issue where if you want to use second argument inside a function, then first argument cannot be ommitted. You can ommit arguments from the end, not from the begining.

Related