Using Array Index as a Second Parameter
You'll learn: How to access the automatically provided index when mapping over arrays, and why it's sometimes useful.
The Index Parameter in .map()
When you call .map() on an array, JavaScript automatically provides two parameters to your callback function: the current item and its position (index) in the array.
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits.map((fruit, index) => {
// fruit is the item ('Apple', 'Banana', etc.)
// index is the position (0, 1, 2)
});
You've been using the first parameter (the item) already. The second parameter gives you the numeric index.
When You Might Need the Index
Displaying position numbers:
const tasks = ['Wake up', 'Code', 'Sleep'];
return (
<ol>
{tasks.map((task, index) => (
<li key={index}>
Task #{index + 1}: {task}
</li>
))}
</ol>
);
Creating alternating styles:
{items.map((item, index) => (
<div key={item.id} className={index % 2 === 0 ? 'even-row' : 'odd-row'}>
{item.name}
</div>
))}
The Index Parameter is Optional
You only need to include index when you're actually using it. If you just need the item, stick with one parameter:
{fruits.map(fruit => <li key={fruit}>{fruit}</li>)}
Key Takeaway: The .map() callback receives (item, index) — use the index when you need position information, but remember it's optional if you only need the item data.