How to use the var to let / const converter
- Paste your code into the JavaScript box.
- Choose Replace var with: const if never reassigned, else let (smart, the default), let, or const.
- Copy the Converted code.
- Check the stats (var replaced, Became const, Became let) and read the warnings under the result.
What it does and when to use it
Since ES2015, let and const are the normal way to declare variables, and most style guides ban var. When you update an old script, a tutorial snippet or a legacy file before refactoring it, this tool makes the change in one pass and shows which names are reassigned.
To go the other way for old browsers, use the ES6 to ES5 converter. For other clean-ups, the ternary to if/else converter expands dense conditions and the JavaScript formatter tidies layout. Check the final code with the JavaScript validator.
How it works
The code is tokenized, so var inside a string, a comment, a regex or a property such as obj.var is never changed. The tool then counts, for every name, how often it is written: plain and compound assignments such as += or ??=, and ++ or --. Smart mode chooses const for a declaration only when all of these hold:
- every name in it has a starting value
- no name is written again after its declaration
- the name is declared with
varonly once - it is not the counter of a classic
for (…; …; …)loop
Otherwise it uses let. A for…in or for…of loop variable can be const, because each pass gets a fresh binding. In const mode every var becomes const, and each one that would fail is listed by line.
Worked examples
Smart mode on the sample.
let total = 0;
const items = getItems();
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
const label = "var stays inside strings";
Four declarations were replaced: 2 became const and 2 became let. total is reassigned with += and i is a loop counter. The word “var” inside the string is untouched.
Forcing const. For var x = 1; var x = 2; var y; y = 3; on separate lines, const mode reports “Line 3: y has no initial value — const will throw there; use let.” and warns that x is declared with var 2 times.
Property and string named var. var s = 'var'; obj.var = 1; in let mode becomes let s = 'var'; obj.var = 1;.
Limits and tips
- Hoisting is not analysed. A warning reminds you to look for code that uses a variable before its declaration.
- Closures in loops change, for the better. With
let, each loop pass gets its owni, which fixes the classic callback bug but can change output in code that relied on the shared value. - Destructuring is handled.
var [c, d] = arr;becomesletifdis reassigned later, andconstotherwise.
Frequently asked questions
Is it safe to replace var with let everywhere?
Why did an object I change become const?
What happens when the same name is declared twice?
Does it understand separate functions?
How do we know nothing is uploaded? Test it yourself on the privacy proof page.