1

why the following code doesn't work? it is going in Illegal invocation exception:

function forEach(array , action) {
    for (var i = 0; i < array.length; i++)
        action(array[i]);
}
forEach([1,2,3], console.log);
Cœur
  • 37,241
  • 25
  • 195
  • 267
fenice85
  • 45
  • 1
  • 4

1 Answers1

1

You need to do it like this:

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

You can call the above as:

forEach([1,2,3], function(value){
    console.log(value)
});

OR

forEach([1,2,3], console.log.bind(console));
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24