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"
29 unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined."
35 const sourceCode = context.getSourceCode();
39 VariableDeclarator(node) {
40 const name = sourceCode.getText(node.id),
41 init = node.init && node.init.name,
42 scope = context.getScope(),
43 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
44 shadowed = undefinedVar && undefinedVar.defs.length > 0,
45 lastToken = sourceCode.getLastToken(node);
47 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
50 messageId: "unnecessaryUndefinedInit",
53 if (node.parent.kind === "var") {
57 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
59 // Don't fix destructuring assignment to `undefined`.
63 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
67 return fixer.removeRange([node.id.range[1], node.range[1]]);