# 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.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

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

Every option, set to its default:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
let total;
if (cart.items.length > 0) {
  total = sum(cart.items);
}
```

Not reported:

{/* good */}
```js
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:

{/* good */}
```js
for (let item of cart.items) {
  render(item);
}
```

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

{/* good */}
```ts
declare let version: string;
```

## Options

```toml 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. |

{/* bad {"options": ["never"]} */}
```js
let count = 0;
```

{/* good {"options": ["never"]} */}
```js
let count;
count = 0;

const limit = 10;
```

### `ignoreForLoopInit`

{/* bad {"options": ["never"], "count": 2} */}
```js
for (let i = 0; i < 3; i++) {
  retry();
}

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

{/* good {"options": ["never", {"ignoreForLoopInit": true}]} */}
```js
for (let i = 0; i < 3; i++) {
  retry();
}

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