JavaScript

JavaScript

Made by DeepSource

Array index possibly out of bounds JS-S1016

Security
Critical
Autofix a04 owasp top 10 cwe-193

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:

  1. Using the < operator.

  2. Using Array.prototype.forEach.

  3. Using a for..of loop instead.

Bad Practice

for (let i = 0; i <= xs.length; ++i) {
  if (isEven(i)) {
    use(xs[i]) // <- out of bounds when i == xs.length
  }
}

Recommended

for (let i = 0; i < xs.length; ++i) {
  if (isEven(i)) {
    use(xs[i]) // <- safe
  }
}

References