Enforce/Disallow Variable Initializations (init-declarations)

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.

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

Rule Details

This rule is aimed at enforcing or eliminating variable initializations during declaration. For example, in the following code, foo is initialized during declaration, while bar is not.

varfoo=1;varbar;bar=2;

This rule aims to bring consistency to variable initializations and declarations.

Options

The rule takes two options:

A string which must be either "always" (the default), to enforce initialization at declaration, or "never" to disallow initialization during declaration. This rule applies to var, let, and const variables, however "never" is ignored for const variables, as unassigned consts generate a parse error.

An object that further controls the behavior of this rule. Currently, the only available parameter is ignoreForLoopInit, which indicates if initialization at declaration is allowed in for loops when "never" is set, since it is a very typical use case.

You can configure the rule as follows:

Variables must be initialized at declaration (default)

{"init-declarations":["error","always"],}

Variables must not be initialized at declaration

{"init-declarations":["error","never"]}

Variables must not be initialized at declaration, except in for loops, where it is allowed