Home > Net >  Javascript forEach Console.log without lambda like syntax
Javascript forEach Console.log without lambda like syntax

Time:10-04

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?

CodePudding user response:

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.

CodePudding user response:

foreach sends in more than just the value. It also sends in the index and original array as arguments 2 and 3. These leak into console.log using the non lambda syntax.

  • Related