Ad

Nodejs Console.log As Callback In ForEach

- 1 answer

I was having a hard time debugging the output of:

content.forEach(console.log);

content is an array of Strings. The problem was it seemed to log out the entire content variable once for every element in the array.

When I finally changed it to

content.forEach(function(a){ console.log(a) });

It began working. What devilry is this?

Ad

Answer

Array.forEach passes the callback three values:

currentValue: The current element being processed in the array.

index: The index of the current element being processed in the array.

array: The array that forEach is being applied to.

Console.log prints out all of the parameters, not just the first one.

Ad
source: stackoverflow.com
Ad