DEV Community

Discussion on: Why can't you break out of the forEach loop?

Collapse
przemek profile image
Przemyslaw Michalak • Edited on

You can't break from forEach because that's the purpose of forEach loop. In JS you have reduce, map, while, do while, for, filter and god knows how many other types of loops. The reason for forEach to exist is to NOT allow you to break from it! It's like complaining that the sit belt in the car have a functionality of saving your life in the accident, well... that's the purpose, not a flaw.

Collapse
mayankav profile image
mayankav Author • Edited on

Hey man! appreciate the analogy. There can indeed be many more reasons why you'd go with a forEach loop (keeping variables scoped, clean abstraction etc..). Tbh, I dont really know the motivation(s) behind the creation of forEach in the first place but that hardly matters. This is just me pointing out a simple mistake that most of us make. I do this over and over even when I know the stuff.