init-declarations

Require or disallow a value in variable declarations

A variable declared without a value is undefined until something assigns to it. If one path through the code skips the assignment, later code reads undefined without any error. Giving every variable a value where it's declared closes that gap.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"init-declarations" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"init-declarations" = ["error", "always"] # "always" or "never"

Examples#

example.js1 problem
let total;
if (cart.items.length > 0) {
  total = sum(cart.items);
}
example.jsNo problems
let total = 0;
if (cart.items.length > 0) {
  total = sum(cart.items);
}

The variable in a for...in or for...of loop gets its value from the loop, so it counts as initialized:

example.jsNo problems
for (let item of cart.items) {
  render(item);
}

In TypeScript, a declare statement can't have a value, so it isn't reported:

example.tsNo problems
declare let version: string;

Options#

bunfig.toml
[lint.rules]
init-declarations = ["error", "never", { ignoreForLoopInit = true }]
OptionWhat it does
"always" (default)Every var and let needs a value.
"never"No var or let can have a value. const is left alone, because it always needs one.
OptionDefaultWhat it does
ignoreForLoopInitfalseWith "never", allow the variables declared in the head of a for, for...in or for...of loop.
example.jswith "never"1 problem
let count = 0;
example.jswith "never"No problems
let count;
count = 0;

const limit = 10;

ignoreForLoopInit#

example.jswith "never"2 problems
for (let i = 0; i < 3; i++) {
  retry();
}

for (let item of cart.items) {
  render(item);
}
example.jswith "never", { "ignoreForLoopInit": true }No problems
for (let i = 0; i < 3; i++) {
  retry();
}

for (let item of cart.items) {
  render(item);
}