Convert var to let or const

Replace var with block-scoped variables let and const.

Refactoring (Convert)
P42 for VS Code
P42 for GitHub
Convert var to let or const

let and const are block-scope variable declarations that can replace 'var' declarations in many cases.

const declares blocked-scoped variables that cannot be re-assigned. let declares block-scoped variables that can be changed. They are available since ES6 and are preferred over function-scope, modifiable var declarations, because they make it easier to reason about the code.

When there are several variables declared in a statement, this refactoring does not change the declaration to prevent formatting breakages and linter issues.

What do I need to consider?

Top-level var declarations can define global variables visible in other files and script sections in some environments.

Most environments (e.g., Node.js), TypeScript code generation, bundling, and ECMAScript Modules prevent this behavior and expect you to use globalThis or its variants to define a global variable.

However, when you directly include scripts in the browser using the script tag (<script src="a-script.js"></script>), var could define globals, and converting to let or const could break your code.


Related Code Assists

Learn More

Available In