Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript forEach Console.log without lambda like syntax

I am going through a JS Book (Modern Javascript for the Impatient) and came across this example, which had a different output than what I was expecting.

const numbers = [1, 2, 3]
numbers.forEach(console.log)

1 0 [ 1, 2, 3 ]
2 1 [ 1, 2, 3 ]
3 2 [ 1, 2, 3 ]

When I use a lambda expression like syntax, I see the right (expected) result.

const numbers = [1, 2, 3]
numbers.forEach(number => console.log(number))

1
2
3

How is the expression being evaluated in the first case? Is the lambda expression syntax always expected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It has nothing to do with arrow function expression (lambda) syntax.

console.log() accepts a series of arguments.

The callback signature for Array.prototype.forEach() is:

forEach((element, index, array) => { /* … */ })

So, for every invocation of the callback (console.log in your example), the series of arguments is displayed in the console.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading