DEV Community

loading...

Discussion on: Common JavaScript Mistakes You May be Making

Collapse
vladimirgal1012 profile image
Vladimir Gal

Wouldn't be a better approach instead of doing

for(const key of Object.keys(obj)) {  
  console.log(obj[key]);  
}

do this ?

Object.keys(obj).map(item => console.log(item));
Collapse
aminnairi profile image
Amin

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 return undefined). So you would rather use something like Array.prototype.forEach.

Object.keys(obj).forEach(item => console.log(item));

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.

Collapse
vladimirgal1012 profile image
Vladimir Gal

Even better. Thanks :)

Collapse
craigmc08 profile image
Craig McIlwrath

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.

Thread Thread
aumayeung profile image
John Au-Yeung Author

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

Collapse
aumayeung profile image
John Au-Yeung Author

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.