When iterating over an array's indices using a for-loop, it is easy to unintentionally perform an out-of-bounds access if the loop's test isn't performed correctly.
The condition i <= array.length
goes from i
to array.length
(inclusive), and may therefore introduce an OOB access if the loop has array[i]
anywhere inside it.
You can fix this by:
Using the <
operator.
Using Array.prototype.forEach
.
Using a for..of
loop instead.
for (let i = 0; i <= xs.length; ++i) {
if (isEven(i)) {
use(xs[i]) // <- out of bounds when i == xs.length
}
}
for (let i = 0; i < xs.length; ++i) {
if (isEven(i)) {
use(xs[i]) // <- safe
}
}