Stuck with High order functions, please help!

The first thing you need to know is that in javascript objects are passed as reference. So you’re getting reference to your object in the function you pass it to. For example

var a = {
  p1 : 'P1'
};

function addProp(x){
  x.p2 = 'P2';
}

console.log(a); //{ p1: 'P1' }
addProp(a);
console.log(a); // { p1: 'P1', p2: 'P2' }

As you can see, whatever changes you make to x inside your addProp function are getting reflected in your original object a. This mechanism is called Pass by reference. Where actual pointer to the parameter is passed. (Easy to understand if you have background in C\C++).

Now, functions in javascript are also Objects so they get passed by reference.

In your forEach function, you pass action as a parameter, which in turn is a function.

  1. How the anonymous function (function(number)) works here

It works the same way as your normal function would work, for example, consider following code snippet

function foo(){
  console.log('I am foo');
}

var bar = function(){
  console.log('I am bar');
}

now to call these functions you do

foo();
bar();

Now in your code, the anonymous function is referred to as action. So if you had

function action(){
}

you would call it like action()

This is exactly what you’re doing in

function forEach ( array , action ) {  
  for ( var i = 0; i < array . length ; i ++)
    action ( array [ i ]) ;
}

The anonymous function (called as action here) is then called with arr[i] as a parameter. And it then modifies the global variable called sum.

  1. when the forEach function is called , will the action(array[i]) get
    replaced with the actual code in the anonymous function? like below

action(array[i]) will be replaced with —> sum = sum + numbers[i] --???

NO! As mentioned about objects are passed by reference. So the same function is reused in this case.
The replacing mechanism that you mentioned here has a difference name in computer science. It is called macro. A macro will be replaced by compiler/interpreter anywhere it is referenced. Function are not replaced in line. In C/C++ these things are defined using #define and in C++ there is a dedicated class of functions called inline functions that behave this way.

Javascript doesn’t support inline function. (Although, I am not sure about this, if anyone knows, correct me if I’m wrong about JS here)

  1. where is the anonymous function getting called here ??

At the same place it is defined.

Hope this helps.

2 Likes