Passing functions to array methods

Hi Guys,

Could you please have a look at the following example code, and explain, why when we pass previously declered function to Array method, we don’t need to invoke this function on every element, but just pass it? How the compiler know to invoke callback function on every element?

const numbers = [2, 7, 9, 171, 52, 33, 14]; const toSquare = num => num * num; // both functions give the same result const squareNums1 = arr =>; const squareNums2 = arr => => toSquare(el));

The code on line 6 is the preferred form. The map iterator looks after the iteration and invocation of the callback on each value in the array.

Line 7 is redundant. In that callback we would write the actual function, not invoke it.

const squareNums2 = arr => => el * el)

If we invoke the callback function when passing it to a method, we’ll be passing the value of the callback function to the method, not the function itself.

1 Like

Many thanks for the explenation!

1 Like

Thanks for your response with the explenation!