eslint/operator-assignment Style
What it does
This rule requires or disallows assignment operator shorthand where possible. It encourages the use of shorthand assignment operators like +=
, -=
, *=
, /=
, etc. to make the code more concise and readable.
Why is this bad?
JavaScript provides shorthand operators that combine variable assignment and simple mathematical operations. Failing to use these shorthand operators can lead to unnecessarily verbose code and can be seen as a missed opportunity for clarity and simplicity.
Examples
Examples of incorrect code for this rule with the default always
option:
x = x + y;
x = y * x;
x[0] = x[0] / y;
x.y = x.y << z;
Examples of correct code for this rule with the default always
option:
x = y;
x += y;
x = y * z;
x = x * y * z;
x[0] /= y;
x[foo()] = x[foo()] % 2;
x = y + x; // `+` is not always commutative (e.g. x = "abc")
Examples of incorrect code for this rule with the never
option:
x *= y;
x ^= (y + z) / foo();
Examples of correct code for this rule with the never
option:
x = x + y;
x.y = x.y / a.b;
Options
This rule has a single string option:
{ type: string, default: "always" }
always
requires assignment operator shorthand where possiblenever
disallows assignment operator shorthand
Example:
"eslint/max-nested-callbacks": ["error", "always"]
"eslint/max-nested-callbacks": ["error", "never"]
How to use
To enable this rule in the CLI or using the config file, you can use:
oxlint --deny operator-assignment
{
"rules": {
"operator-assignment": "error"
}
}