javascript - Why doesn't console.log work when passed as a parameter to forEach? -


this out of curiosity, of have idea why code won't work?

[1, 2, 3, 4, 5].foreach(console.log);  // prints 'uncaught typeerror: illegal invocation' in chrome 

on other hand, seems work fine:

[1, 2, 3, 4, 5].foreach(function(n) { console.log(n) }); 

so... ?

it's worth pointing out there difference in behavior in implementation of console.log. under node v0.10.19 not error; see this:

> [1,2,3,4,5].foreach(console.log); 1 0 [ 1, 2, 3, 4, 5 ] 2 1 [ 1, 2, 3, 4, 5 ] 3 2 [ 1, 2, 3, 4, 5 ] 4 3 [ 1, 2, 3, 4, 5 ] 5 4 [ 1, 2, 3, 4, 5 ] 

this because callback foreach three-parameter function taking value, index, , array itself. function console.log sees 3 parameters , dutifully logs them.

under chrome browser console, however, get

> [1,2,3,4,5].foreach(console.log); typeerror: illegal invocation 

and in case, bind will work:

 > [1,2,3,4,5].foreach(console.log.bind(console));  1 0 [ 1, 2, 3, 4, 5 ]  2 1 [ 1, 2, 3, 4, 5 ]  3 2 [ 1, 2, 3, 4, 5 ]  4 3 [ 1, 2, 3, 4, 5 ]  5 4 [ 1, 2, 3, 4, 5 ] 

but there alternative way: note second parameter foreach takes value of this use in callback:

> [1,2,3,4,5].foreach(console.log, console) 1 0 [ 1, 2, 3, 4, 5 ] 2 1 [ 1, 2, 3, 4, 5 ] 3 2 [ 1, 2, 3, 4, 5 ] 4 3 [ 1, 2, 3, 4, 5 ] 5 4 [ 1, 2, 3, 4, 5 ] 

which works in chrome console , node me. of course, i'm sure want values, i'm afraid best solution is, indeed:

> [1,2,3,4,5].foreach(function (e) {console.log(e)}); 1 2 3 4 5 

whether node's behavior bug, or takes advantage of fact console.log not specified ecma interesting in own right. varying behavior, , fact have aware of whether callback uses this important , means have fall direct coding, if verbose keyword function.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -