There is an example in JavaScriptIsSexy for a simple callback that I'd like to understand a bit better:
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});
In this case, how are the parameters eachName
and index
understood to mean the elements of the array (people's names as strings) and index numbers, respectively? Would that have to be specified via arguments in the call that just isn't shown here, but is expected if you want the output shown in the comment?
Because that is how the forEach
function is defined, as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach :
> callback is invoked with three arguments: > > - the element value > - the element index > - the array being traversed
Obviously, the names eachName
and index
don't mean anything specially by themselves. They're meaning is purely positional. You can call them and use them as whatever you want. Whatever name you put first will be used as the parameter name for the element value, the 2nd as the element index, and the 3rd as the array.
Even though you're not yet using it, there is also a 3rd parameter that you could declare and use - the entire array - if you want it. Similarly, if you don't care about the index, you don't need to define it either.
This is how forEach
works.
You give it a function to call for each element of the array.
That function will be called with the following arguments (in order):
In your case, you have
function (eachName, index)
So this means that eachName
is the current element, index
is the index and you don't make use of the third parameter.
In addition to these three parameters, you also have the option of having a this
appear inside of your function. That is specified by an optional second argument to forEach
(after your callback function).
FavScripts.com is a free tool to save your favorite scripts and commands, then quickly find and copy-paste your commands with just few clicks.
Boost your productivity with FavScripts.com!