Jjimex007

var-to-let-const-js

Convert var declarations to const or let based on reassignment analysis

varletconstmodernizationmigrationes6javascript
Public
0 executions

Run locally

npx codemod var-to-let-const-js

var-to-let-const-js

Converts var declarations to const or let in JavaScript/JSX files, choosing
const when a variable is never reassigned and let when it is.

Installation

bash

What it does

  • var x = 1; where x is never reassigned → const x = 1;
  • var x = 1; x = 2;let x = 1;
  • var x, y = 2; with mixed reassignment → split into separate let/const
    statements, preserving declaration order (JS doesn't allow mixing keywords
    in one var statement).
  • for (var i = 0; i < n; i++)for (let i = 0; ...) (the counter is
    reassigned by the increment).
  • for (var x of iterable) / for (var x in obj)for (const x of ...)
    unless x is reassigned inside the loop body, in which case let.
  • x++, x--, x += 1, and other compound assignments count as
    reassignment.

Files it targets

**/*.{js,jsx,mjs,cjs}, excluding node_modules, dist, and build
(see workflow.yaml).

Preserve / no-op cases

  • Already let/const: left untouched.
  • var accessed outside its declaring block: if a var is declared
    inside an if/for/while/switch/try/catch block but read or
    written outside that block within the same function, it's left as var
    — converting it would change behavior, since let/const are
    block-scoped while var is function-scoped.
  • Redeclared var: if the same name is declared with var more than
    once in the same function/program scope, both declarations are left as
    var (repeating a let/const declaration is a SyntaxError).
  • Shadowing across scopes (e.g. the same name declared in an outer
    scope and independently in a nested function) is analyzed and converted
    independently per scope — that's not a redeclaration.

This codemod does not target TypeScript (.ts/.tsx) files; the registry
already has var-to-let-const for that.

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.