0

Sorry about this really stupid question, but why this code is not working?

var ar = [1,2,3];
ar.forEach(console.log);

Thank you in advance.

Mutex
  • 430
  • 2
  • 5
  • 14
  • 4
    Define "not working". `console.log` requires context, though. Use `console.log.bind(console)` or (ES6) `a => console.log(a)` – John Dvorak Feb 23 '16 at 15:42
  • what do you mean by "doesn't work"? I can think of a couple issues: 1) log expects a parameter that isn't there and 2) log only gets called in the debugger in some browsers – Dave Bush Feb 23 '16 at 15:43
  • Thanks @JanDvorak , that's what I needed: "requires context, though" – Mutex Feb 23 '16 at 15:49

1 Answers1

-1

Because You need to pass to the .forEach an anonymous function:

ar.forEach(function(el, index, array){
  console.log(index);
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Suleiman
  • 1,003
  • 2
  • 15
  • 29
  • Yes, I know this. But console.log is also a function which can accept this args. Why I can not pass it instead? – Mutex Feb 23 '16 at 15:45
  • @Mutex http://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal-invocation-in-javascript - first answer – Suleiman Feb 23 '16 at 15:49