2 * @fileoverview Rule to flag when initializing to undefined
8 const astUtils = require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
19 description: "disallow initializing variables to `undefined`",
20 category: "Variables",
22 url: "https://eslint.org/docs/rules/no-undef-init"
31 const sourceCode = context.getSourceCode();
35 VariableDeclarator(node) {
36 const name = sourceCode.getText(node.id),
37 init = node.init && node.init.name,
38 scope = context.getScope(),
39 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
40 shadowed = undefinedVar && undefinedVar.defs.length > 0,
41 lastToken = sourceCode.getLastToken(node);
43 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
46 message: "It's not necessary to initialize '{{name}}' to undefined.",
49 if (node.parent.kind === "var") {
53 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
55 // Don't fix destructuring assignment to `undefined`.
59 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
63 return fixer.removeRange([node.id.range[1], node.range[1]]);