As you can see, we are repeating the item keyword a lot. We can pass the console.log as a parameter to our Array.prototype.forEach which is a higher order function like so.
Object.keys(obj).forEach(console.log);
Which would be the equivalent syntax to what we wrote.
The second simplification is called eta-reduction, but in this case it is not valid eta-reduction because result of the expression changes.
In the original, it will log the value of each item. In the reduced form, it logs the value, index, and entire array for each item (Array.prototype.forEach actually passes 3 parameters). This is a mistake to be mindful of.
Map would be useful if you did use the return value for each mapped values.
In this case, the
console.log
method won't return anything (or returnundefined
). So you would rather use something likeArray.prototype.forEach
.As you can see, we are repeating the
item
keyword a lot. We can pass theconsole.log
as a parameter to ourArray.prototype.forEach
which is a higher order function like so.Which would be the equivalent syntax to what we wrote.
Even better. Thanks :)
The second simplification is called eta-reduction, but in this case it is not valid eta-reduction because result of the expression changes.
In the original, it will log the value of each item. In the reduced form, it logs the value, index, and entire array for each item (
Array.prototype.forEach
actually passes 3 parameters). This is a mistake to be mindful of.Yea. That example works in JavaScript because it lets use pass in anything to a function.
It's very easy to make a mistake passing in a function like that
The last snippet assume that everyone knows what the first argument of console.log should be.
So it's leas clear. But both are fine if we're just logging the value straight up.