Coding Rules

Rules for writing robust, maintainable code

Rule 1: The termination condition of a loop should be easy to reason about

Infinite loops can have harmful consequences, such as blocking the browser tab, making a server unresponsive or consuming a huge amount of resources.

When writing a loop, make sure that it's obvious the loop terminates.

❌ Don't:

let found = null;
while (found === null) {
  const next = items.getNextElement();
  if (next === "expected") found = next;
}

Although the above code is correct if "expected" always exists in items, it isn't obvious when reading the code that this invariant is true. Furthermore, as the code is changed, this invariant may cease to be true and an infinite loop may occur.

✅ Do:

let found = null;
while (const item of items) {
  if (item === "expected") {
    found = item;
    break;
  }
}