Search code examples
javascriptlambda

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?


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.