Array.prototype.forEach() **không hỗ trợ break/continue/return** để thoát sớm. Ném exception là cách duy nhất (bad practice).
Giải pháp thay thế
1. _.find / _.findIndex (Lodash) — dừng khi tìm thấy
_.find([1,2,3,4], (el) => {
if (el === 2) return true; // break
});
2. for...of loop (ES6) — hỗ trợ break/continue
for (const el of arr) {
if (el === 2) break;
// process
}
3. Array.prototype.some() / every()
some: dừng khi callback return truthy.every: dừng khi callback return falsy.
arr.some(el => { if (el === 2) return true; }); // break on 2
4. Throw exception (last resort)
try {
arr.forEach(el => { if (el === 2) throw new Error('break'); });
} catch (e) { /* ignore */ }
Khuyến nghị: Dùng for...of cho logic phức tạp cần break. Dùng some/find cho early exit đơn giản.