Tip 27: Reduce Loop Clutter with for...in and for...each

In this tip, you’ll learn how to maintain clarity with loops over iterables using for...in and over objects using for...of.

Using array methods

Hopefully by now you’re convinced that array methods can handle most of your iterations in clear and predictable ways. Sometimes, however, an array method may be either inefficient or cumbersome.

There may be times you want to exit out of a loop when a result doesn’t match what you need. In those cases, it makes no sense to keep iterating over information.

Alternatively, an array method may be overly complex when you’re working with a collection that isn’t an array. Remember that just because a structure isn’t an array doesn’t mean you can’t use array methods. If you’re working with an object, you can use Object.keys() to create an array of keys and then perform whatever method you want. Or you can use the spread operator to convert a Map to an array of pairs. If you need a refresher, head back to Tip 14, Iterate Over Key-Value Data with Map and the Spread Operator.

In fact, those are great approaches. The popular Airbnb style guide, for example, insists that you always use array methods and restricts the use of the for...of and for...in loops.

That opinion isn’t shared by all. Sometimes it’s not worth the hassle to convert structures to arrays and it’s worth knowing other options.

Example

Consider an application where you can select and compare multiple sets of information. Perhaps you’re building an application that has a list of consulting firms. A user can select multiple firms and compare and contrast services.

Knowing what you know now, you’d probably use a Map to hold the various firms as users click on options. After all, you’re constantly adding and deleting information, which is an action a Map can handle easily.

As the user clicks on firms they’re interested in, you could add the firms to a simple map that uses the ID of the firm as a key and the name of the firm as the value.

Get hands-on with 1200+ tech skills courses.