blob: 2c2204cf0fe2d27ca7932f932ce5566d0de28fc1 [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
Tim van der Lippe0ceb4652022-01-06 14:23:36 +010014/** @type {import('../shared/types').Rule} */
Yang Guo4fd355c2019-09-19 10:59:03 +020015module.exports = {
16 meta: {
17 type: "suggestion",
18
19 docs: {
20 description: "disallow initializing variables to `undefined`",
Yang Guo4fd355c2019-09-19 10:59:03 +020021 recommended: false,
22 url: "https://eslint.org/docs/rules/no-undef-init"
23 },
24
25 schema: [],
Tim van der Lippe16aca392020-11-13 11:37:13 +000026 fixable: "code",
27
28 messages: {
29 unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined."
30 }
Yang Guo4fd355c2019-09-19 10:59:03 +020031 },
32
33 create(context) {
34
35 const sourceCode = context.getSourceCode();
36
37 return {
38
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"),
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010044 shadowed = undefinedVar && undefinedVar.defs.length > 0,
45 lastToken = sourceCode.getLastToken(node);
Yang Guo4fd355c2019-09-19 10:59:03 +020046
47 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
48 context.report({
49 node,
Tim van der Lippe16aca392020-11-13 11:37:13 +000050 messageId: "unnecessaryUndefinedInit",
Yang Guo4fd355c2019-09-19 10:59:03 +020051 data: { name },
52 fix(fixer) {
53 if (node.parent.kind === "var") {
54 return null;
55 }
56
57 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
58
59 // Don't fix destructuring assignment to `undefined`.
60 return null;
61 }
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010062
63 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
64 return null;
65 }
66
Yang Guo4fd355c2019-09-19 10:59:03 +020067 return fixer.removeRange([node.id.range[1], node.range[1]]);
68 }
69 });
70 }
71 }
72 };
73
74 }
75};