I would like to print an array line by line with carriage return.
Simple implementation is [1,2,3].forEach(function(x) {console.log(x)})
to get this as output
1
2
3
Now if I use the syntactic sugar of ES6 fat arrows,
michel$ node
> [1,2,3].forEach(x => console.log(x))
1
2
3
undefined
>
> [1,2,3].forEach(console.log)
1 0 [ 1, 2, 3 ]
2 1 [ 1, 2, 3 ]
3 2 [ 1, 2, 3 ]
undefined
When omitting the function parameter in the forEach
callback, it looks like the second version is returning a cartesian product of itself.
In other functional languages like Scala this is totally ok, why is this "wrong" in JavaScript?
michel$ scala
scala> Array(1,2,3).foreach(x => println(x))
1
2
3
scala> Array(1,2,3).foreach(println)
1
2
3
Arrow functions allow us to use the fat arrow => operator to quickly define JavaScript functions, with or without parameters. We are able to omit the curly braces and the function and return keywords when creating a new JavaScript function to write shorter function syntax.
forEach() accepts up to three arguments: the current element in the array upon which . forEach() was called, the index of that element in the array, and the array itself.
One of the most heralded features in modern JavaScript is the introduction of arrow functions, sometimes called 'fat arrow' functions, utilizing the new token => . These functions two major benefits - a very clean concise syntax and more intuitive scoping and this binding.
Therefore, the value of the this keyword has also changed, as it's now bound to the global scope. Arrow functions don't have their own this context. They inherit the value of this from the parent, and it's because of this feature that they make a great choice in situations like the one above.
It seems that this code here:
[1,2,3].forEach(console.log)
is the same as:
[1,2,3].forEach((value, index, array) => console.log(value, index, array))
It is not "wrong", it is just "unusual" in comparison to Scala or Java (method references) which seem to support method references with one single parameter. Javascript just seem to copy all parameters across to the referenced method (e.g. console.log
) and if this method supports varargs, everything gets processed.
But if you do not like this behaviour you can fix it in Javascript. Create a simple function which accepts one single parameter:
function print(t) { console.log(t) }
and then execute:
[1,2,3].forEach(print)
And this prints the result, that will let you feel at home if you are coming from a Scala background:
1
2
3
You can use the ES6 'fat' arrow Like this.
const data = [1,2,3,4]
data.forEach(item => {
console.log(item)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With