My question is about the map
method of arrays in JavaScript.
You can pass it a function that takes a second argument, the index of the current element of the array being processed, but... to what purpose? What happens when you do it and what's the difference when you don't?
What would you use this feature for?
Sometimes the index of the element matters. For example, this map replaces every second element with 0:
Output:
The index of the current item is always passed to the callback function, the only difference if you don't declare it in the function is that you can't access it by name.
Example:
Output:
Demo: http://jsfiddle.net/Guffa/k4x5vfzj/
Here is a description of of the
map
function:The map function takes a callback function as argument (and not an index as argument, as originally stated in the question before it was edited). The callback function has an index as a parameter - the callback is called automatically, so you don't provide the index yourself. If you only need the current value, you can omit the other parameters.