no-undef-init.js 2.2 KB

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