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 totalVariable total should be initialized on declaration.;
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 }]| Option | What 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. |
| Option | Default | What it does |
|---|---|---|
ignoreForLoopInit | false | With "never", allow the variables declared in the head of a for, for...in or for...of loop. |
example.jswith
"never"1 problemlet count = 0Variable count should not be initialized on declaration.;example.jswith
"never"No problemslet count;
count = 0;
const limit = 10;ignoreForLoopInit#
example.jswith
"never"2 problemsfor (let i = 0Variable i should not be initialized on declaration.; i < 3; i++) {
retry();
}
for (let itemVariable item should not be initialized on declaration. of cart.items) {
render(item);
}example.jswith
"never", { "ignoreForLoopInit": true }No problemsfor (let i = 0; i < 3; i++) {
retry();
}
for (let item of cart.items) {
render(item);
}