When iterating an array with a need to break out at some point, I have always used the good old for loop instead of some other Array iteration variant. This is mainly due to the fact that .forEach() does not have a break out option – forcing the entire array to be iterated.
But… while listening to Syntax I heard that the .some() method can be used in place of the .forEach() method when a break out is needed. Cool!
So, looking into this. Let’s first view the result of using the .forEach() method.
.ForEach()
const kingsOfDenmark = ['Gorm the Old', 'Harald Bluetooth', 'Sweyn Forkbeard', 'Cnut the Great', 'Valdemar the Great'];
const wanted = 'Sweyn Forkbeard';
kingsOfDenmark.forEach(king => {
if (king === wanted) {
console.log('Found', king);
// forEach() does not support breaking out
}
console.log('After if...');
});
// OUTPUT OF THE ABOVE WILL BE
// After if...
// After if...
// Found Sweyn Forkbeard
// After if...
// After if...
// After if...
It shows that even after locating the wanted value, .forEach() will continue to iterate the rest of the array. This is due to no break out option being available for the .forEach() method.
for loop
As mentioned earlier, I used to stick with using the for loop when needing to break out of an array iteration. I usually use the following approach for this.
const kingsOfDenmark = ['Gorm the Old', 'Harald Bluetooth', 'Sweyn Forkbeard', 'Cnut the Great', 'Valdemar the Great'];
const wanted = 'Sweyn Forkbeard';
for (let i = 0; i < kingsOfDenmark.length; i++) {
let king = kingsOfDenmark[i];
if (king === wanted) {
console.log('Found', king);
// The wanted value has been located - let's break out
break;
}
console.log('After if...');
}
// OUTPUT OF THE ABOVE WILL BE
// After if...
// After if...
// Found Sweyn Forkbeard
So this shows that we can stop iteration when the wanted value is located – skipping the rest of the array.
.some()
I heard on an episode of Syntax that the Array .some() method would stop iteration when returning true. This is really cool since I like using the same pattern when dealing with arrays. And mixing for loops with array methods just seems a bit off to me. Now, I’m able to use array methods instead of the for loop – which makes me happy (I have not idea whether it’s better performing or not).
Let try it out.
const kingsOfDenmark = ['Gorm the Old', 'Harald Bluetooth', 'Sweyn Forkbeard', 'Cnut the Great', 'Valdemar the Great'];
const wanted = 'Sweyn Forkbeard';
kingsOfDenmark.some(king => {
if (king === wanted) {
console.log('Found', king);
// The wanted value has been located - let's break out
return true;
}
console.log('After if...');
return false;
});
// OUTPUT OF THE ABOVE WILL BE
// After if...
// After if...
// Found Sweyn Forkbeard
It works beautifully! Some day I need to see if this babels into a for loop for ES5, but for now, I’m just happy since my code will “feel” more aligned.
Happy coding 🙂