Understanding parameters in an anonymous function (callback example)

0
=
0
+
0
No specific Bitcoin Bounty has been announced by author. Still, anyone could send Bitcoin Tips to those who provide a good answer.
0

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?

2 answers

2
=
0
=
$0
Internet users could send Bitcoin Tips to you if they like your answer!

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.

SEND BITCOIN TIPS
User rating:
don't forget about the "fourth argument"; this, which is provided by the 2nd argument to forEach().
0

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):

  1. the current element
  2. the index of the current element
  3. the whole array

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).

SEND BITCOIN TIPS
User rating:
don't forget about forEach callback's "fourth argument"; this, which is provided by the 2nd argument to forEach().
0

Too many commands? Learning new syntax?

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!

Post Answer