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

JaseyJS
  • 71
  • 7
  • 1
    Your function is being called by `.forEach()`, which passes parameters when it calls the callback. – Pointy Mar 03 '18 at 12:47

3 Answers3

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)
hungersoft
  • 531
  • 4
  • 8
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

Simone Pontiggia
  • 204
  • 2
  • 10
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.

Adi219
  • 4,712
  • 2
  • 20
  • 43