Map's Callback Parameters
You'll learn exactly what information map() passes to your callback function on every iteration.
When you use map() on an array, the method doesn't just hand your callback function the current element—it actually provides three pieces of information each time it calls your function:
- The current element (what you usually care about)
- The index of that element in the array
- The entire original array being mapped
Understanding the Three Parameters
Think of map() as a helpful assistant who gives you context: "Here's the item you asked to process, it's at position 5, and by the way, here's the full list if you need to reference it."
const numbers = [10, 20, 30];
numbers.map((element, index, array) => {
console.log('Element:', element);
console.log('Index:', index);
console.log('Array:', array);
return element * 2;
});
// First iteration logs:
// Element: 10
// Index: 0
// Array: [10, 20, 30]
When to Use Each Parameter
Most of the time, you only need the element:
const doubled = [1, 2, 3].map(num => num * 2);
// [2, 4, 6]
Sometimes the index is useful:
const withPosition = ['a', 'b', 'c'].map((letter, i) => {
return `${i}: ${letter}`;
});
// ['0: a', '1: b', '2: c']
Rarely, you might need the original array (perhaps to compare the current element against other elements).
You can name these parameters whatever you want, but their order matters: first is always the element, second is the index, third is the array.
Key Takeaway: map() passes three arguments to your callback—element, index, and the original array—but you only need to accept the ones you'll actually use.