1. Use .map or .forEach instead of for Loops

Every complex application requires a decent amount of looping over sets of data, usually in the case of arrays or objects. With for loops, code becomes quickly unreadable and hard to follow.

For example, take a look at the code below and tell me which one you would prefer.

Looping over arrays

The code above loops over the array of numbers and prints each number to the console.

But what if we have more complex arrays, like an array of objects? Use map , filter , reduce for iteration purposes.

Finally, here’s what’s being printed to the console. The result is the same, but the code is much cleaner with the functional programming approach.

Looping over arrays

The only exception to using for loops is when we iterate over objects. That’s because forEach , map , reduce , and filter are methods we can call on for arrays only.

ERROR: “TypeError: dogs.map is not a function”

In the case of looping over objects, we could use for...in loops.

Looping over dogs with for…in loop

A better approach to iterate over objects would be to use the following methods:

Object.keys — returns an array of a given object’s own enumerable property names , iterated in the same order as that provided by a normal loop

— returns an array of a given object’s own enumerable property , iterated in the same order as that provided by a normal loop Object.values — returns an array of a given object’s own enumerable property values , in the same order as that provided by a for...in loop

— returns an array of a given object’s own enumerable property , in the same order as that provided by a loop Object.entries — returns an array of a given object’s own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

The above methods grab the keys or values from the object, place them into an array, and return the array as a result.

Transforming the dogs object into an array with Object.values()

Now that we have an array, we can iterate the values, with map or forEach to grab the values.

Here are a couple of different approaches to iterating over objects with different goals in mind.