DEV Community

loading...
Thinkster

Purpose-Driven For Loop Replacement

josepheames profile image Joe Eames ・3 min read

"When you have a hammer, everything looks like a nail." One of the common things that happens when someone gets comfortable with a tool like for loops is that they start using them for everything. But there are quite a few scenarios where for loops are frequently used, but there are better options. I'm going to cover a few of those today.

Finding a unique item
The first one is finding a specific item in an array. This is a very common scenario. Let's say your user wants to view detail information about a specific item in their cart. You need to grab the item from the cart array with a specific ID. It's common to go use a for loop to get this.

Something like this:

image

Now, this is certainly a reasonable method to use to find this item.

But let's use a better structure. The find() method is much more optimized for this scenario:

image

Which can even be shortened to this:

image

This syntax is much simpler and concise. Find will return the first item that matches the query. MOST of the time we want to use this when we need to find a specific item in an array. Generally, this is used when we are finding an item by some unique criteria, like the id shown above. Even though we can use this same find function to find an item by non-unique criteria, such as finding the first item that has the outOfStock flag, generally this use case is better served by a different function.

Does any item in our array match a specific condition?
When we want to find an item by some non-unique criteria, like an out of stock item, what we are REALLY trying to do is find out if ANY item is out of stock, perhaps so we can ask the user if they want to split out the order, or wait until out of stock items get in stock.

In a for loop, this looks like this:

image

Sure, this works, but in this case, what we really want is the some() function.

image

The some method returns true if any item in the array matches the given criteria. Otherwise, it returns false. The longhand of the above is the following:

image

Create a subset from an array
Now Once the user tells us that they want us to send the in-stock items now, we have to cut the cart down to just the items that are in-stock.

Again, default tool is the for loop

image

But we can do this much easier with the filter option:

image

Simple and succinct.

So, need to do one of these tasks? Don't use the for loop. Don't use the forEach loop. Use the right structure.

If you're interested in REALLY learning JavaScript, check out our 100 Algorithms challenge.

And don't forget to check out all our awesome courses on JavaScript, Node, React, Angular, Vue, Docker, etc.

Happy Coding!

Enjoy this discussion? Sign up for our newsletter here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Discussion (0)

Forem Open with the Forem app