Prefer local state to global state

suggest change

Local state makes dependencies explicit, reduces accidental coupling, and is easier to test. Prefer returning a result over mutating a global variable:

function sum(items) {
  let total = 0;

  for (const item of items) {
    total += item;
  }

  return total;
}

Do not cache array lengths or object properties solely because older performance advice recommended it. Modern JavaScript engines optimize common access patterns, and manual caching can make code harder to read or can change behavior if the collection is mutated during iteration. Measure representative code before applying a performance optimization.

Global state is sometimes necessary, but it should have a clear owner and lifecycle. Pass dependencies as arguments or encapsulate them in a module rather than reading and writing unrelated globals throughout the program.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents