When I try
[1,2,3].forEach(alert); it opens message box for every item of the array as expected.
But when I try
[1,2,3].forEach(console.log); I receive following error
Uncaught TypeError: Illegal invocation Why?
Personally I get Invalid calling object.
See, [1,2,3].forEach(console.log) is essentially a shorthand way of iterating over the array and for each item running console.log.call(theArray,theItem). However, console.log requires that this be an object of type Console, thus the error.
Try [1,2,3].forEach(function(i) {console.log(i);})
[1,2,3].forEach(console.log.bind(console)); Could you please add it into your answer to help others running into this question?Actually, it doesn't work in Firefox, or at least not as you might expect:
[1,2,3].forEach(console.log) Gives you:
1 0 [1, 2, 3] 2 1 [1, 2, 3] 3 2 [1, 2, 3] Why? MDN has your answer:
callback is invoked with three arguments:
the element value
the element index
the array being traversed
However,
[1,2,3].forEach(function(i) { console.log(i); }); Works exactly as you'd expect in both Firefox and Chrome.
[1,2,3].forEach(console.log)works fine in Firefox.console.logreturns error itself unless debug console is on. I suspect it is not an ordinary function, but I'm not sure. Maybe each browser implement it different way?console.log(1, 2, 3);to see three separate elements. That may not fit your use case, though.