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?
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);})
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.