Skip to content

Commit

Permalink
Fix: no-undef-init should not apply to class fields (refs #14857) (#1…
Browse files Browse the repository at this point in the history
…4994)

* Fix: no-undef-init should not apply to class fields (refs #14857)

* update docs
  • Loading branch information
mdjermanovic committed Sep 2, 2021
1 parent 4338b74 commit e9764f3
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 94 deletions.
25 changes: 21 additions & 4 deletions docs/rules/no-undef-init.md
Expand Up @@ -19,13 +19,12 @@ It's considered a best practice to avoid initializing variables to `undefined`.

## Rule Details

This rule aims to eliminate variable declarations that initialize to `undefined`.
This rule aims to eliminate `var` and `let` variable declarations that initialize to `undefined`.

Examples of **incorrect** code for this rule:

```js
/*eslint no-undef-init: "error"*/
/*eslint-env es6*/

var foo = undefined;
let bar = undefined;
Expand All @@ -35,11 +34,29 @@ Examples of **correct** code for this rule:

```js
/*eslint no-undef-init: "error"*/
/*eslint-env es6*/

var foo;
let bar;
const baz = undefined;
```

Please note that this rule does not check `const` declarations, destructuring patterns, function parameters, and class fields.

Examples of additional **correct** code for this rule:

```js
/*eslint no-undef-init: "error"*/

const foo = undefined;

let { bar = undefined } = baz;

[quux = undefined] = quuux;

(foo = undefined) => {};

class Foo {
bar = undefined;
}
```

## When Not To Use It
Expand Down
72 changes: 9 additions & 63 deletions lib/rules/no-undef-init.js
Expand Up @@ -33,91 +33,37 @@ module.exports = {

const sourceCode = context.getSourceCode();

/**
* Get the node of init target.
* @param {ASTNode} node The node to get.
* @throws {Error} (Unreachable.)
* @returns {ASTNode} The node of init target.
*/
function getIdNode(node) {
switch (node.type) {
case "VariableDeclarator":
return node.id;
case "PropertyDefinition":
return node.key;
default:
throw new Error("unreachable");
}
}

/**
* Get the node of init value.
* @param {ASTNode} node The node to get.
* @throws {Error} (Unreachable.)
* @returns {ASTNode} The node of init value.
*/
function getInitNode(node) {
switch (node.type) {
case "VariableDeclarator":
return node.init;
case "PropertyDefinition":
return node.value;
default:
throw new Error("unreachable");
}
}

/**
* Get the parent kind of the node.
* @param {ASTNode} node The node to get.
* @throws {Error} (Unreachable.)
* @returns {string} The parent kind.
*/
function getParentKind(node) {
switch (node.type) {
case "VariableDeclarator":
return node.parent.kind;
case "PropertyDefinition":
return "field";
default:
throw new Error("unreachable");
}
}

return {

"VariableDeclarator, PropertyDefinition"(node) {
const idNode = getIdNode(node),
name = sourceCode.getText(idNode),
initNode = getInitNode(node),
initIsUndefined = initNode && initNode.type === "Identifier" && initNode.name === "undefined",
parentKind = getParentKind(node),
VariableDeclarator(node) {
const name = sourceCode.getText(node.id),
init = node.init && node.init.name,
scope = context.getScope(),
undefinedVar = astUtils.getVariableByName(scope, "undefined"),
shadowed = undefinedVar && undefinedVar.defs.length > 0,
lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
lastToken = sourceCode.getLastToken(node);

if (initIsUndefined && parentKind !== "const" && !shadowed) {
if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
context.report({
node,
messageId: "unnecessaryUndefinedInit",
data: { name },
fix(fixer) {
if (parentKind === "var") {
if (node.parent.kind === "var") {
return null;
}

if (idNode.type === "ArrayPattern" || idNode.type === "ObjectPattern") {
if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {

// Don't fix destructuring assignment to `undefined`.
return null;
}

if (sourceCode.commentsExistBetween(idNode, lastToken)) {
if (sourceCode.commentsExistBetween(node.id, lastToken)) {
return null;
}

return fixer.removeRange([idNode.range[1], lastToken.range[1]]);
return fixer.removeRange([node.id.range[1], node.range[1]]);
}
});
}
Expand Down
32 changes: 5 additions & 27 deletions tests/lib/rules/no-undef-init.js
Expand Up @@ -22,7 +22,11 @@ ruleTester.run("no-undef-init", rule, {
valid: [
"var a;",
{ code: "const foo = undefined", parserOptions: { ecmaVersion: 6 } },
"var undefined = 5; var foo = undefined;"
"var undefined = 5; var foo = undefined;",

// doesn't apply to class fields
{ code: "class C { field = undefined; }", parserOptions: { ecmaVersion: 2022 } }

],
invalid: [
{
Expand Down Expand Up @@ -148,32 +152,6 @@ ruleTester.run("no-undef-init", rule, {
output: "let a//comment\n, b;",
parserOptions: { ecmaVersion: 6 },
errors: [{ messageId: "unnecessaryUndefinedInit", data: { name: "a" }, type: "VariableDeclarator" }]
},

// Class fields
{
code: "class C { field = undefined; }",
output: "class C { field; }",
parserOptions: { ecmaVersion: 2022 },
errors: [{ messageId: "unnecessaryUndefinedInit", data: { name: "field" }, type: "PropertyDefinition" }]
},
{
code: "class C { field = undefined }",
output: "class C { field }",
parserOptions: { ecmaVersion: 2022 },
errors: [{ messageId: "unnecessaryUndefinedInit", data: { name: "field" }, type: "PropertyDefinition" }]
},
{
code: "class C { #field = undefined; }",
output: "class C { #field; }",
parserOptions: { ecmaVersion: 2022 },
errors: [{ messageId: "unnecessaryUndefinedInit", data: { name: "#field" }, type: "PropertyDefinition" }]
},
{
code: "class C { '#field' = undefined; }",
output: "class C { '#field'; }",
parserOptions: { ecmaVersion: 2022 },
errors: [{ messageId: "unnecessaryUndefinedInit", data: { name: "'#field'" }, type: "PropertyDefinition" }]
}
]
});

0 comments on commit e9764f3

Please sign in to comment.