no-var

Require let or const instead of var

warn by defaultfixable

A var belongs to the whole function, not to the block it's written in, and you can read it before the line that declares it. let and const are scoped to their block and can't be used before they're declared, which turns a class of silent bugs into errors.

--fix rewrites var to let where that can't change what the code does.

This rule is on by default in TypeScript files.

Configure#

On by default as a warning. To turn it off:

bunfig.toml
[lint.rules]
"no-var" = "off" # or "error"

Examples#

example.js1 problem
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 3, 3, 3
}
example.jsNo problems
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 0, 1, 2
}

declare var isn't reported, and neither is a var inside declare global, declare module or declare namespace. It runs no code. It tells TypeScript that a global exists, and only a var becomes a property of globalThis and can be declared in more than one file:

example.tsNo problems
declare var BUILD_ID: string;

console.log(globalThis.BUILD_ID);

With an ESLint config the rule reports what ESLint reports, so that a // eslint-disable-next-line no-var above a declare var is still needed: every var, except one directly inside declare global, which only ESLint 8 reports. With an oxlint config it reports what oxlint reports: declare var, but no var inside declare global, declare module or declare namespace.

example.ts1 problem
declare var BUILD_ID: string;