Successfully added
JavaScript
by Patrik
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.
Referenced in:
Comments