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
Reported:
let total;
if (cart.items.length > 0) {
total = sum(cart.items);
}
Not reported:
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:
for (let item of cart.items) {
render(item);
}
In TypeScript, a declare statement can't have a value, so it isn't reported:
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. |
let count = 0;
let count;
count = 0;
const limit = 10;
ignoreForLoopInit
for (let i = 0; i < 3; i++) {
retry();
}
for (let item of cart.items) {
render(item);
}
for (let i = 0; i < 3; i++) {
retry();
}
for (let item of cart.items) {
render(item);
}