Do you know how to stop forEach loops in JavaScript?

Tram Ho

Use forEach

For javascript programmers, it is certainly not new to forEach . In addition to regular loops like for , while , forEach is a pretty good loop to shorten the time to write code. Please see the following example.

  • For example when using the for loop

  • Or with the while loop

As you saw above are 2 examples of for and while . When working with for and while we must always pay attention to the index variable of the array to be able to get elements in the array, and if not careful we can falsify the desired results. What about forEach ? Let’s see the following example:

With just one simple command line, there is no need to put new variables and increase index types

Stops the loop

With for and while is simple, just we use the break command is. For example:

But with forEach you know how to stop it ? ))))) Of course, you can’t use break like with for or while . If you do not know, I will show you some ways to stop it. Let’s go to the first way.

1. Use if

Actually this way it does not actually stop the loop, it just skips and does not execute the code inside, but it ends up still as we expected. For the array with large data, this way is not really effective. And this may be considered the least effective way to stop forEach . Come to the next way.

2. Use throw, try … catch

Unlike the above method, which only bypasses the code and does not stop the loop, this method completely stops the loop and the result is still the same. But this is a controversial way because no one wants to throw a loop error and it has a lot of risks. And come up with the last way I know to stop forEach .

3. Do not use forEach anymore

?????? Sounds pretty funny, right. The way to stop forEach is to stop using it. So if not used forEach anymore, what to use now ??? You guys still have a way to calm down. Instead of using forEach , we can use every or some . Please see the following example:

Conclude

Above I have introduced you how to use loops in javascript as well as how to stop those loops. And also depending on the case that you should choose for , while or use forEach to use appropriately. If you find it interesting, please upload and share to help me be more motivated to make better and better posts ?

Share the news now

Source : Viblo