Three Ways to Exit an Array Loop Before Completion in JavaScript
Learn to use break, some(), and every()
Working with loops — what I often refer to as iteration structures — is a fundamental skill in programming. Iterating over a data structure is such a common task that it becomes like muscle memory, reflexively using the same technique over and over.
Sometimes, when we’re inside of a loop, we want to exit early. This requirement is common when searching for things or establishing exit criteria within a set number of attempts.
We’ll go over the most common method of exiting a JavaScript loop — or any control structure, really — and two lesser-known methods to expand your toolkit.
Break Keyword
The break keyword is the classic technique for early exiting. We see break statements everywhere, from switch statements to while and for loops. This command will exit its immediate structure.
As an example, let’s write a loop to print out all the numbers in an array. As an added requirement, we want to stop if/when a value greater than four is encountered. We’ll be using a for…of loop to iterate over our array.const nums = [1,2,3,4,5,6];for(const n of nums) {
console.log(n);
if(n > 4) {
break;
}
}// 1, 2, 3, 4, 5
Break statements are flexible, straightforward, and somewhat ubiquitous in the programming world. It’s a technique you want to have on speed dial and it’s the best place to start when it comes to exiting structures.
The next two methods were introduced alongside the methods map, filter, and reduce.
These three methods are quite popular; however, their two lesser-known siblings, .some() and .every(), can be used in instances where looping through an array needs to end early.
The .some() Method
All of the iteration JavaScript methods accept a callback, which is a function that will be called for each item in the array. With the .some() method, the function will be executed until a true result is returned.const nums = [1,2,3,4,5,6];nums.some(n => {
console.log(n);
return n > 4;
});// 1, 2, 3, 4, 5
If you’re intimidated by the syntax from the example, here’s a brief rundown:
nis our parameter list. In this callback example, it is each item in the array. Since there is a single parameter, we can omit the parentheses.=>is an arrow function notation, another way of defining a function. It takes the place of the traditionalfunctionkeyword.- Curly braces work just the same way, defining the boundaries of our function
- Finally, the
});is our closing syntax to close the function’s body, then the method’s call, and finally the overall statement.
The .every() Method
The .every() method is effectively the opposite of using the .some() method. In this method, the array is iterated over until true is returned.const nums = [1,2,3,4,5,6];
nums.every(n => {
console.log(n);
return n < 5;
});// 1, 2, 3, 4, 5
Do you use .some() or .every()? Are these functions worth replacing existing practices for or a tool that collects dust? Let us know in the comments below.