blob: 1fdccb867b3c2463a59ce7b2a54f4e0d09ac3e61 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview Rule to flag when initializing to undefined
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8const astUtils = require("./utils/ast-utils");
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 type: "suggestion",
17
18 docs: {
19 description: "disallow initializing variables to `undefined`",
20 category: "Variables",
21 recommended: false,
22 url: "https://eslint.org/docs/rules/no-undef-init"
23 },
24
25 schema: [],
26 fixable: "code"
27 },
28
29 create(context) {
30
31 const sourceCode = context.getSourceCode();
32
33 return {
34
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"),
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010040 shadowed = undefinedVar && undefinedVar.defs.length > 0,
41 lastToken = sourceCode.getLastToken(node);
Yang Guo4fd355c2019-09-19 10:59:03 +020042
43 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
44 context.report({
45 node,
46 message: "It's not necessary to initialize '{{name}}' to undefined.",
47 data: { name },
48 fix(fixer) {
49 if (node.parent.kind === "var") {
50 return null;
51 }
52
53 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
54
55 // Don't fix destructuring assignment to `undefined`.
56 return null;
57 }
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010058
59 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
60 return null;
61 }
62
Yang Guo4fd355c2019-09-19 10:59:03 +020063 return fixer.removeRange([node.id.range[1], node.range[1]]);
64 }
65 });
66 }
67 }
68 };
69
70 }
71};