diff --git a/docs/rules/no-self-assign.md b/docs/rules/no-self-assign.md index f7132e2b166..8b90cdfd3f1 100644 --- a/docs/rules/no-self-assign.md +++ b/docs/rules/no-self-assign.md @@ -24,6 +24,10 @@ foo = foo; [a, ...b] = [x, ...b]; ({a, b} = {a, x}); + +foo &&= foo; +foo ||= foo; +foo ??= foo; ``` Examples of **correct** code for this rule: @@ -50,6 +54,10 @@ obj[a] = obj["a"]; obj.a().b = obj.a().b; a().b = a().b; +// `&=` and `|=` have an effect on non-integers. +foo &= foo; +foo |= foo; + // Known limitation: this does not support computed properties except single literal or single identifier. obj[a + b] = obj[a + b]; obj["a" + "b"] = obj["a" + "b"]; diff --git a/lib/rules/no-self-assign.js b/lib/rules/no-self-assign.js index d9e261dfaae..060cc8e353e 100644 --- a/lib/rules/no-self-assign.js +++ b/lib/rules/no-self-assign.js @@ -174,7 +174,7 @@ module.exports = { return { AssignmentExpression(node) { - if (node.operator === "=") { + if (["=", "&&=", "||=", "??="].includes(node.operator)) { eachSelfAssignment(node.left, node.right, props, report); } } diff --git a/tests/lib/rules/no-self-assign.js b/tests/lib/rules/no-self-assign.js index 04aa2dee402..0fe04040d7a 100644 --- a/tests/lib/rules/no-self-assign.js +++ b/tests/lib/rules/no-self-assign.js @@ -25,6 +25,8 @@ ruleTester.run("no-self-assign", rule, { "a += a", "a = +a", "a = [a]", + "a &= a", + "a |= a", { code: "let a = a", parserOptions: { ecmaVersion: 6 } }, { code: "const a = a", parserOptions: { ecmaVersion: 6 } }, { code: "[a] = a", parserOptions: { ecmaVersion: 6 } }, @@ -167,6 +169,23 @@ ruleTester.run("no-self-assign", rule, { code: "class C { #field; foo() { [this.#field] = [this.#field]; } }", parserOptions: { ecmaVersion: 2022 }, errors: [{ messageId: "selfAssignment", data: { name: "this.#field" } }] + }, + + // logical assignment + { + code: "a &&= a", + parserOptions: { ecmaVersion: 2021 }, + errors: [{ messageId: "selfAssignment", data: { name: "a" } }] + }, + { + code: "a ||= a", + parserOptions: { ecmaVersion: 2021 }, + errors: [{ messageId: "selfAssignment", data: { name: "a" } }] + }, + { + code: "a ??= a", + parserOptions: { ecmaVersion: 2021 }, + errors: [{ messageId: "selfAssignment", data: { name: "a" } }] } ] });