for-loop-equality-operator

Try in Playground
javascript-best-practicesError ProneInformational

0

No tags

CWE-835

Testing a for loop termination using an equality operator (== or !=) is dangerous because it could set up an infinite loop.

Consider using comparison operators, less than (<) or greater than (>), to decrease the likelihood you accidentally write an infinite loop.

Equality operators are ignored when the right side of the test is null.

Ast Rule: for loop


for-loop-equality-operator

How to write a rule
const EQUALITY_OPERATORS = [
  "!=",
  "=="
];

function visit(node, filename, code) {
  if (!node.test.elements) return;

  const operator = node.test.elements[0]?.operator;
  if (!operator) return;

  if (!operator.right || operator.right.value === "null") return;

  if (!EQUALITY_OPERATORS.some(op => operator.value.includes(op))) return;

  const error = buildError(
    operator.start.line,
    operator.start.col,
    operator.end.line,
    operator.end.col,
    `Using an equality operator to terminate a for loop can cause infinite loops `,
    "WARNING",
    "ERROR_PRONE"
  );

  addError(error);
}

index.js

Expected test result: no error

for (var i = 0; arr[i] != null; i++) {
  // ...
}

for (var i = 0; (item = arr[i]) != null; i++) {
  // ...
}

index.js

Expected test result: has error

for (var i = 1; i != 10; i += 2) {
  //...
}

for (var i = 1; i !== 10; i += 2) {
  //...
}

for (var i = 1; i == 10; i += 2) {
  //...
}

for (var i = 1; i === 10; i += 2) {
  //...
}
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.