Michael Farhat
Michael Farhat

Reputation: 41

getting an error when passing some parameters

I am a beginner so it this may not be a very smart question .. If I have this function

function repeat (n,action) {
      for(i=0;i<n;i++){
          action(i) 
      }
 }

if I implement it in this way repeat (3,console.log) it works. why do I get an error if I pass it this parameters:

let arr = [0]; 
repeat(3,arr.push);

since action(i) will be replaced -as I think- with arr.push(i)

Upvotes: 3

Views: 30

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

The Array.prototype.push method is not a function and cannot be used as a callback, unless it is binded. It expects a this to be passed in as the scope of the call.

See: Why can't I use Array.prototype.join.call as a callback of a Promise?

You have two options:

  • repeat(3, arr.push.bind(arr)); (binded-method callback)
  • repeat(3, v => arr.push(v)); (lambda-style callback)

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i)
  }
}

repeat(3, console.log);

console.log

let arr = [0];
repeat(3, arr.push.bind(arr));
console.log(arr);

Upvotes: 5

Related Questions