2 * @fileoverview A rule to control the style of variable initializations.
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
13 * Checks whether or not a given node is a for loop.
14 * @param {ASTNode} block A node to check.
15 * @returns {boolean} `true` when the node is a for loop.
17 function isForLoop(block) {
18 return block.type === "ForInStatement" ||
19 block.type === "ForOfStatement" ||
20 block.type === "ForStatement";
24 * Checks whether or not a given declarator node has its initializer.
25 * @param {ASTNode} node A declarator node to check.
26 * @returns {boolean} `true` when the node has its initializer.
28 function isInitialized(node) {
29 const declaration = node.parent;
30 const block = declaration.parent;
32 if (isForLoop(block)) {
33 if (block.type === "ForStatement") {
34 return block.init === declaration;
36 return block.left === declaration;
38 return Boolean(node.init);
41 //------------------------------------------------------------------------------
43 //------------------------------------------------------------------------------
50 description: "require or disallow initialization in variable declarations",
51 category: "Variables",
53 url: "https://eslint.org/docs/rules/init-declarations"
81 additionalProperties: false
90 initialized: "Variable '{{idName}}' should be initialized on declaration.",
91 notInitialized: "Variable '{{idName}}' should not be initialized on declaration."
97 const MODE_ALWAYS = "always",
100 const mode = context.options[0] || MODE_ALWAYS;
101 const params = context.options[1] || {};
103 //--------------------------------------------------------------------------
105 //--------------------------------------------------------------------------
108 "VariableDeclaration:exit"(node) {
110 const kind = node.kind,
111 declarations = node.declarations;
113 for (let i = 0; i < declarations.length; ++i) {
114 const declaration = declarations[i],
116 initialized = isInitialized(declaration),
117 isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent);
120 if (mode === MODE_ALWAYS && !initialized) {
121 messageId = "initialized";
122 } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) {
123 messageId = "notInitialized";
126 if (id.type === "Identifier" && messageId) {