for
loop in modern JavaScript is rarely talked about although it’s only useful in asynchronous operation scenarios.
But what breaking out early consider the following example:
Matching two array
const smallArray = [0, 2];
const largeArray = Array.from({ length: 1000 }, (_, i) => i);
const areEqual = (a, b) => {
let result = true;
a.forEach((x, i) => {
if (!result) return;
if (b[i] === undefined || x !== b[i]) result = false;
});
return result;
}
areEqual(largeArray, smallArray); // false
// Will loop over all items in `largeArray`
The code isn’t optimized, but it highlights the issue of array methods, such as [].forEach()
being unable to break out of the loop early.
To counteract this, we could use a for
loop and an early return
instead:
...
const areEqual = (a, b) => {
for (let i in a) {
if (b[i] === undefined || a[i] !== b[i]) return false;
}
return true;
}
areEqual(largeArray, smallArray); // false
// Will only loop until the first mismatch is encountered
Rehmaanali on September 3, 2021
🔥 1073 views