Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters inside callback function in Javascript

Tags:

javascript

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.

like image 719
darkknight Avatar asked Jul 26 '18 22:07

darkknight


1 Answers

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.

like image 102
Leon Avatar answered Oct 24 '22 09:10

Leon