Use let or const Instead of var

ID

javascript.no_var

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

JavaScript

Tags

code-smell, modern-js

Description

Reports any var declaration:

var counter = 0;            // FLAW
var name = "x", age = 1;    // FLAW

Rationale

var is function-scoped and hoisted, which is the root cause of several JavaScript footguns:

  • the classic for-loop captures every callback to the post-loop value (for (var i …​) setTimeout(() ⇒ i)),

  • a var redeclaration silently overwrites the original binding,

  • a hoisted var is undefined in the line before its declaration,

  • shadowing happens at function scope rather than block scope, so a var x inside an if quietly leaks outward.

let (mutable) and const (immutable binding) are block-scoped and not hoisted into the temporal dead zone, eliminating all four issues. Modern JavaScript code uses them by default.

Remediation

Pick the right keyword:

let counter = 0;       // mutable
const name = "x";      // never reassigned

For loop iteration variables let is the right choice — each iteration produces a fresh binding, so closures capture the value correctly:

for (let i = 0; i < n; i++) {
  setTimeout(() => console.log(i), 0);   // logs 0, 1, 2, ...
}

Notes

The rule fires on the entire VariableStatement (one issue per var …​ statement, regardless of how many comma-separated names follow it). let and const parse as a different AST node and are not reported.