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;wherexis never reassigned →const x = 1;var x = 1; x = 2;→let x = 1;var x, y = 2;with mixed reassignment → split into separatelet/const
statements, preserving declaration order (JS doesn't allow mixing keywords
in onevarstatement).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 ...)
unlessxis reassigned inside the loop body, in which caselet.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. varaccessed outside its declaring block: if avaris declared
inside anif/for/while/switch/try/catchblock but read or
written outside that block within the same function, it's left asvar
— converting it would change behavior, sincelet/constare
block-scoped whilevaris function-scoped.- Redeclared
var: if the same name is declared withvarmore than
once in the same function/program scope, both declarations are left as
var(repeating alet/constdeclaration is aSyntaxError). - 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