Search code examples
javascripthigher-order-functionsarray-push

When console.log passed as a parameter it works, but when array.push is passed a parameter it doesn't work why?


I may be asking a silly question.but I am a beginner.

I saw this example in eloquent JavaScript in the chapter about higher order function.

There is a repeat function that takes 2 arguments. 1. number of time we want the repetition 2. action that we want to repeat

When console.log is passed as 2nd argument code works just fine. it produces perfect output.

but when array.push is passed as 2nd argument code throws an error, we are required to pass a function as 2nd argument to make array.push work.

Please help understanding this concept.

//code here works...
function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

repeat(3, console.log);

//so why code below does not work...?
function repeat(n, action) {
    for (let i = 0; i < n; i++) {
      action(i);
    }
  }

let labels = [];
repeat(5, labels.push);

console.log(labels);

/*
In my understanding labels.push is also a function just like console.log, so it should push i 5 times(i.e 0-4) into labels array.
Please help me where am I wrong.
*/

//Why we require to pass a function as described below.
function repeat(n, action) {
    for (let i = 0; i < n; i++) {
      action(i);
    }
  }

let labels = [];
repeat(5, i => labels.push(i));
console.log(labels);

Solution

  • it is because labels.push requires a context.

    if you do repeat(5, labels.push.bind(labels)), you will see that it works.

    i leave it to you read up on what fn.call(), fn.bind() and fn.apply() do.