0
var num = [2,4,6,8,10,12];
function print (n) {
console.log (n);
}
num.forEach(print);

My understanding was we give function's parameters to pass in arguments But above code is not passing in any arguments. I know the output, Question is how array of num's each value is passing into parameter 'n', while im just calling in function it self. To simplify How parameter 'n' is getting each value of array num ? Thank You

1
  • 1
    Your function is being called by .forEach(), which passes parameters when it calls the callback. Commented Mar 3, 2018 at 12:47

3 Answers 3

0

The 'print' function that you are passing as an argument for 'forEach' is a callback function with a specific set of arguments. When forEach iterates over each item of the array it passes the currentValue of the array during a specific iteration as the first argument to the callback function (i.e., 'print' in your case.)

Following is the general syntax of array forEach:

 array.forEach(function(currentValue, index, arr), thisValue)
Sign up to request clarification or add additional context in comments.

Comments

0

A simplified version of the forEach method will look like the following

foreach(this: array, fn : (element) => void) : void {
   for (i = 0; i < this.length; i++) { 
     fn(this[i])
   }
}

So is the for each method that is responsible to pass each element of the array as the parameter n

Comments

0

.forEach() maps the function which it receives to the elements of the object which is invoking it.

In your case, the elements of the num array are automatically passed as arguments to the print function, as num is invoking its .forEach() method and print is the function being supplied as an argument to the .forEach() method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.