Skip to content

eslint/init-declarations Style

What it does

Require or disallow initialization in variable declarations

Why is this bad?

In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, foo is initialized during declaration, while bar is initialized later.

Examples

var foo = 1; var bar; if (foo) { bar = 1; } else { bar = 2; }

Examples of incorrect code for the default "always" option:

js
/*eslint init-declarations: ["error", "always"]*/
function foo() {
  var bar;
  let baz;
}

Examples of incorrect code for the "never" option:

js
/*eslint init-declarations: ["error", "never"]*/
function foo() {
  var bar = 1;
  let baz = 2;
  for (var i = 0; i < 1; i++) {}
}

Examples of correct code for the default "always" option:

js
/*eslint init-declarations: ["error", "always"]*/

function foo() {
  var bar = 1;
  let baz = 2;
  const qux = 3;
}

Examples of correct code for the "never" option:

js
/*eslint init-declarations: ["error", "never"]*/

function foo() {
  var bar;
  let baz;
  const buzz = 1;
}

Examples of correct code for the "never", { "ignoreForLoopInit": true } options:

js
/*eslint init-declarations: ["error", "never", { "ignoreForLoopInit": true }]*/
for (var i = 0; i < 1; i++) {}

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny init-declarations
json
{
  "rules": {
    "init-declarations": "error"
  }
}

References

Released under the MIT License.