]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/rules/operator-assignment.md
import 7.12.1 upstream release
[pve-eslint.git] / eslint / docs / rules / operator-assignment.md
CommitLineData
eb39fafa
DC
1# require or disallow assignment operator shorthand where possible (operator-assignment)
2
3JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, `x = x + 4` can be shortened to `x += 4`. The supported shorthand forms are as follows:
4
5```text
6 Shorthand | Separate
7-----------|------------
8 x += y | x = x + y
9 x -= y | x = x - y
10 x *= y | x = x * y
11 x /= y | x = x / y
12 x %= y | x = x % y
6f036462 13 x **= y | x = x ** y
eb39fafa
DC
14 x <<= y | x = x << y
15 x >>= y | x = x >> y
16 x >>>= y | x = x >>> y
17 x &= y | x = x & y
18 x ^= y | x = x ^ y
19 x |= y | x = x | y
20```
21
22## Rule Details
23
24This rule requires or disallows assignment operator shorthand where possible.
25
6f036462
TL
26The rule applies to the operators listed in the above table. It does not report the logical assignment operators `&&=`, `||=`, and `??=` because their short-circuiting behavior is different from the other assignment operators.
27
eb39fafa
DC
28## Options
29
30This rule has a single string option:
31
32* `"always"` (default) requires assignment operator shorthand where possible
33* `"never"` disallows assignment operator shorthand
34
35### always
36
37Examples of **incorrect** code for this rule with the default `"always"` option:
38
39```js
40/*eslint operator-assignment: ["error", "always"]*/
41
42x = x + y;
43x = y * x;
44x[0] = x[0] / y;
45x.y = x.y << z;
46```
47
48Examples of **correct** code for this rule with the default `"always"` option:
49
50```js
51/*eslint operator-assignment: ["error", "always"]*/
52
53x = y;
54x += y;
55x = y * z;
56x = (x * y) * z;
57x[0] /= y;
58x[foo()] = x[foo()] % 2;
59x = y + x; // `+` is not always commutative (e.g. x = "abc")
60```
61
62### never
63
64Examples of **incorrect** code for this rule with the `"never"` option:
65
66```js
67/*eslint operator-assignment: ["error", "never"]*/
68
69x *= y;
70x ^= (y + z) / foo();
71```
72
73Examples of **correct** code for this rule with the `"never"` option:
74
75```js
76/*eslint operator-assignment: ["error", "never"]*/
77
78x = x + y;
79x.y = x.y / a.b;
80```
81
82## When Not To Use It
83
84Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis.