0

In JavaScript, why does .forEach(console.log) only give you the output you expect when you wrap console.log in another function?

a = [0, 1, 2, 3, 4, 5, 6]
[ 0, 1, 2, 3, 4, 5, 6 ]
a.forEach(console.log)
0 0 [ 0, 1, 2, 3, 4, 5, 6 ]
1 1 [ 0, 1, 2, 3, 4, 5, 6 ]
2 2 [ 0, 1, 2, 3, 4, 5, 6 ]
3 3 [ 0, 1, 2, 3, 4, 5, 6 ]
4 4 [ 0, 1, 2, 3, 4, 5, 6 ]
5 5 [ 0, 1, 2, 3, 4, 5, 6 ]
6 6 [ 0, 1, 2, 3, 4, 5, 6 ]
undefined
a.forEach(function(n) { console.log(n) })
0
1
2
3
4
5
6
undefined

What causes this difference in output?

Zaz
  • 46,476
  • 14
  • 84
  • 101
  • 1
    It does work..! But with 3 arguments...Which are [`(currentValue, index, array)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters) – Rayon Nov 26 '16 at 20:50
  • 3
    [site:stackoverflow.com javascript foreach(console.log)](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+foreach%28console.log%29) –  Nov 26 '16 at 20:53
  • @axlj it's not weird at all, `forEach` and `console.log` are working just as intended... – Andrew Li Nov 26 '16 at 20:54
  • @axlj — "_definitely some weird behaviour_" ? What is that ? – Rayon Nov 26 '16 at 20:54
  • @AndrewLi -- read the linked post. makes sense now. Thanks! – AJ X. Nov 26 '16 at 20:57
  • *console* is a host object whose behaviour isn't specified, so only the implementors know the expected behaviour. – RobG Nov 26 '16 at 21:04

0 Answers0