Lets consider forEach method of Javascript:
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName);
});
Can somebody please explain from where do the params eachName and index come from, since they were not defined anywhere in the code.
I understand it may quite obvious to many people but I am not not able to grasp this concept.
You should read the documentation on forEach. The function declared in forEach is called for every element in the array. forEach will call the inner function with the value of the array item as the first function parameter and the index of the array alement as the second function parameter.
So forEach will iterate over the array, similar to a for loop, and for every item in the array it will take the value and the index and pass it to the declared function.
Your confusion most likely come from the parameter names, but those names can be anything. The first parameter will always be the current item array value and the second the index.
To write your own function you would create a for loop that calls the defined function.
If we look at your original code and pull out the function (this is good for testing BTW).
var friends = ["Mike", "Stacy", "Andy", "Rick"];
function doStuff(eachName, index){
console.log(index + 1 + ". " + eachName);
}
// Does is still the same as yours
friends.forEach(doStuff);
// This loop does exactly what a forEach polyfill would do
for(var i = 0; i < friends.length; i++) {
doStuff(a[i], i);
}
Have a look at the MDN foreach polyfill for a complete example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With