mediumLogic ErrorsJavaScript
The mutated loop
A developer asked an AI assistant to remove all expired coupons from a list in place. The suggested code compiles cleanly and appears to work in quick manual tests, but a bug report shows some expired coupons are still slipping through.
coupons.js
function removeExpiredCoupons(coupons) {
coupons.forEach((coupon, index) => {
if (coupon.expired) {
coupons.splice(index, 1);
}
});
return coupons;
}Why do some expired coupons survive this cleanup?
splice inside forEach shifts every later element's index down by one, so forEach skips the element that slides into the just-removed slot.
forEach does not support mutating the array it's iterating over and throws silently.
coupon.expired is checked before the array is fully loaded into memory.
splice(index, 1) removes two elements instead of one when index is 0.