Javascript foreach with break

break forEach Loop Javascript

JavaScript’s forEach method allows you to iterate over an array and perform a specific operation on each element.

It is a useful method for executing a certain action on each element of an array, but sometimes you may want to break out of the loop early, before all elements have been processed.

In this tutorial, we will learn how to break out of a forEach loop in JavaScript.

Javascript forEach break

There are two ways to break out of a forEach loop in JavaScript.

Let’s see how to use these two methods to break out of a forEach loop in JavaScript.

1. Using break keyword

The most common way to break out of a forEach loop is to use the break statement.

The break statement terminates the current loop and transfers program control to the statement following the terminated statement.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers.forEach((number) => < // break out of the loop if number is greater than 5 if (number >5) < break; >console.log(number); >);

In the above example, the loop will only iterate over elements 1 through 5, and will stop when it encounters element 6.

Читайте также:  Create captcha in php

2. Using return keyword

Another way to break out of a forEach loop is to use the return statement.

The return statement terminates the execution of a function and returns a value from that function.

Here is an example of using the return statement to break out of a forEach loop:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers.forEach((number) => < if (number >5) < return; >console.log(number); >);

In the above example, the loop will break at element 6 using the return statement.

Situations where you need to break out of a forEach loop

There are many situations where you may want to break out of a forEach loop. Here are some of the most common situations:

  1. When the loop has completed its intended purpose and there is no need to continue iterating over the remaining elements. For example, you might want to break out of a forEach loop that searches for a specific element in an array once that element is found.
  2. When the loop encounters an error or invalid condition that requires the loop to be terminated early. For example, you might want to break out of a forEach loop that processes user input if the input is invalid.
  3. When the loop is taking too long to execute and you want to terminate it early in order to improve performance or avoid an infinite loop. For example, you might want to break out of a forEach loop that is processing a large dataset if it has been running for too long.

Conclusion

To summarize, we have learned how to break out of a forEach loop in JavaScript.

There are two ways to break out of a forEach loop in JavaScript.

  1. By breaking out of the loop using break keyword
  2. By returning from loop execution using return keyword

Источник

How to Break Out of a JavaScript forEach() Loop

JavaScript’s forEach() function executes a function on every element in an array. However, since forEach() is a function rather than a loop, using the break statement is a syntax error:

[1, 2, 3, 4, 5].forEach(v => < if (v > 3) < // SyntaxError: Illegal break statement break; > >);

We recommend using for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() that needs to stop after a certain point and refactoring to use for/of is not an option, here’s 4 workarounds:

1. Use every() instead of forEach()

The every() function behaves exactly like forEach() , except it stops iterating through the array whenever the callback function returns a falsy value.

// Prints "1, 2, 3" [1, 2, 3, 4, 5].every(v => < if (v > 3) < return false; > console.log(v); // Make sure you return true. If you don't return a value, `every()` will stop. return true; >);

With every() , return false is equivalent to a break , and return true is equivalent to a continue .

Another alternative is to use the find() function, which is similar but just flips the boolean values. With find() , return true is equivalent to break , and return false is equivalent to continue .

2. Filter Out The Values You Want to Skip

Instead of thinking about how to break out of a forEach() , try thinking about how to filter out all the values you don’t want forEach() to iterate over. This approach is more in line with functional programming principles.

The findIndex() function takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the slice() function copies part of the array.

// Prints "1, 2, 3" const arr = [1, 2, 3, 4, 5]; // Instead of trying to `break`, slice out the part of the array that `break` // would ignore. arr.slice(0, arr.findIndex(v => v > 3)).forEach(v => < console.log(v); >);

3. Use a shouldSkip Local Variable

If you can’t use every() or slice() , you can check a shouldSkip flag at the start of your forEach() callback. If you set shouldSkip to true , the forEach() callback returns immediately.

// Prints "1, 2, 3" let shouldSkip = false; [1, 2, 3, 4, 5].forEach(v => < if (shouldSkip) < return; > if (v > 3) < shouldSkip = true; return; > console.log(v); >);

This approach is clunky and inelegant, but it works with minimum mental overhead. You can use this approach if the previous approaches seem too clever.

4. Modify the array length

The forEach() function respects changes to the array’s length property. So you can force forEach() to break out of the loop early by overwriting the array’s length property as shown below.

const myNums = [1, 2, 3, 4, 5]; myNums.forEach((v, index, arr) => < console.log(v); if (val > 3) < arr.length = index + 1; // Behaves like `break` > >

While this approach works, it also mutates the array! If you change the array’s length, you effectively truncate the array: subsequent operations, like for/of or JSON.stringify() will only go through the shortened version of the array. Using this approach to break out of a forEach() loop is not recommended.

More Fundamentals Tutorials

Источник

How to exit a forEach Loop in Javascript

Break forEach Loop Javascript

It goes without saying that the majority of coding is dealing with loops. There are all kinds of loops with all sorts of different syntaxes. It’s challenging to make sense of it all, but part of becoming proficient in programming is knowing what syntax to use, especially when there are multiple options. One loop in javascript is the forEach loop. It’s used to iterate over arrays. It provides a nice syntax, but issues arise when we try to get a bit more complicated, such as breaking out of the loop. Let’s learn how to exit a forEach loop in javascript.

Table of contents

How to Exit a forEach Loop in Javascript

Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.

Let’s look at the following code snippet.

let data = [ ,, ] data.forEach(obj => < console.log(obj.name) if (obj.name === 'Steph') < break; >>)  

You would expect the code to stop executing after it finds the name “Steph”; however, it throws an Unsyntactic break error.

Solution

As in most things in programming, there is, of course, a workaround. We can throw and catch an exception while iterating our array. Let’s take a look at how we could achieve this.

let data = [ ,, ] try < data.forEach(obj => < console.log(obj.name) if (obj.name === 'Steph') < throw 'Break'; >>) > catch (e)  

As you can see here, we wrapped our forEach statement in a try catch block. Where we would typically do a break, we perform a “throw ‘Break’

We then jump down to our catch and check what our error is. If it’s anything other than “Break“, we throw it up the error chain. Otherwise, we continue with our code execution.

Although this solution works, it’s not very clean. Let’s take a look at a few better alternatives.

Alternative #1: for…of loop (Preferred)

The for…of loop would be the preferred solution to this problem. It provides clean easy to read syntax and also lets us use break once again.

let data = [ ,, ] for (let obj of data)  

Another added benefit of using the for…of loop is the ability to perform await operations within it. We would not be able to use the await syntax within a forEach loop.

Alternative #2: every

We can also use the “every” array prototype. Let’s take a look at that code snippet.

let data = [ ,, ] data.every(obj => < console.log(obj.name) return !(obj.name === 'Steph') >)  

The every prototype will test each element against our function and expect a boolean return. When a value is returned false, the loop will be broken. In this case, we inverse our name test and return false when the name is equal to “Steph”, the loop breaks, and we continue our code.

Alternative #3: some

Very similar to the every prototype, we could also use the “some” array prototype. The some prototype is almost identical to the every prototype. The only difference is that a true return will break the loop. Let’s take a look at the code.

let data = [ ,, ] data.some(obj => < console.log(obj.name) return (obj.name === 'Steph') >)  

You can see that the function returns true when it reaches the “Steph” name and breaks the loop. Whether you choose some or every is entirely dependent on what you believe to be the most readable.

You now know how to exit a forEach loop in Javascript. You have multiple alternative solutions and also the primary workaround. Choose the option that fits your use case the best. Remember, code readability is very important, so choose wisely. Happy Coding!

Источник

Оцените статью