• Coding Beauty
  • Posts
  • You can actually BREAK a forEach loop in JavaScript

You can actually BREAK a forEach loop in JavaScript

Highlights: New puzzle, stopping a forEach loop, and if statement alternatives

Sponsored by

Invest before this company becomes a household name

What if you had the opportunity to invest in the biggest electronics products before they launched into big box retail, would you?

Ring changed doorbells and Nest changed thermostats. Early investors in these companies earned massive returns, but the opportunity to invest was limited to a select, wealthy few. Not anymore. RYSE has just launched in 100+ Best Buy stores, and you're in luck — you can still invest at only $1.50/share before their name becomes known nationwide.

They have patented the only mass market shade automation device, and their exclusive deal with Best Buy resembles that which led Ring and Nest to their billion-dollar buyouts.

Can you solve this puzzle?

Can you break out of a “forEach” loop in JavaScript?

It’s an amazing question to challenge just how well you really know JavaScript.

Because we’re not talking for loops — or this would have been ridiculously easy: you just break:

But you wouldn’t dare do this with forEach, or disaster happens:

What about return… mhmm.

What do you think is going to happen here:

return should easily end the loop at 5 and take us to the outer log right?

Wrong:

I'm not one of those who go on screaming about how horrible if statements are -- in many cases, they are simply the best choice out of all the ways to create control flow.

Yet there are lots of situations where a different construct will do a noticeably better job of expressing our code's intent -- something we can't ignore as long we write code for humans. Not to mention lower verbosity and shorter code.

So, let's look at some powerful if statement alternatives.

1. The AND (&&) operator

This one is unique to JavaScript.

We quickly go from this:

To this:

We've eradicated the nested and compacted the branching logic into a one-liner.

You want to use this when there's an if but no matching else; especially when the if block has only one line.

Even if there are multiple lines you can abstract them into a separate function and apply && again. After all the console.log() in our example is an abstraction itself.

Thank you for taking the time to read today’s issue.

Don’t let the bugs byte,
Tari Ibaba