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

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

How come this code executes the way I want it to in the codeacademy javascript console, but not the one in chrome? In chrome it keeps saying illegal invocation so I'm not sure if I'm doing some wrong or not. Any help please?

joyfulchute
  • 89
  • 1
  • 7
  • When asking about error messages, always paste in the exact wording of the error; there may be details in there which mean nothing to you, but someone can use to explain the problem. – IMSoP Jul 18 '15 at 23:28

1 Answers1

2

console.log expects this to be bound to console when you invoke it. (When you call it inside your forEach, you're not accessing it as a method of console anymore, so its internal this will be bound to the global object.)

Use console.log.bind(console) in place of console.log.

doldt
  • 4,466
  • 3
  • 21
  • 36