UNPKG

2.03 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag when initializing to undefined
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8const astUtils = require("../ast-utils");
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 docs: {
17 description: "disallow initializing variables to `undefined`",
18 category: "Variables",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/no-undef-init"
21 },
22
23 schema: [],
24
25 fixable: "code"
26 },
27
28 create(context) {
29
30 const sourceCode = context.getSourceCode();
31
32 return {
33
34 VariableDeclarator(node) {
35 const name = sourceCode.getText(node.id),
36 init = node.init && node.init.name,
37 scope = context.getScope(),
38 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
39 shadowed = undefinedVar && undefinedVar.defs.length > 0;
40
41 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
42 context.report({
43 node,
44 message: "It's not necessary to initialize '{{name}}' to undefined.",
45 data: { name },
46 fix(fixer) {
47 if (node.parent.kind === "var") {
48 return null;
49 }
50
51 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
52
53 // Don't fix destructuring assignment to `undefined`.
54 return null;
55 }
56 return fixer.removeRange([node.id.range[1], node.range[1]]);
57 }
58 });
59 }
60 }
61 };
62
63 }
64};