]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # require or disallow assignment operator shorthand where possible (operator-assignment) |
2 | ||
3 | JavaScript 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 | ||
24 | This rule requires or disallows assignment operator shorthand where possible. | |
25 | ||
6f036462 TL |
26 | The 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 | ||
30 | This 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 | ||
37 | Examples of **incorrect** code for this rule with the default `"always"` option: | |
38 | ||
39 | ```js | |
40 | /*eslint operator-assignment: ["error", "always"]*/ | |
41 | ||
42 | x = x + y; | |
43 | x = y * x; | |
44 | x[0] = x[0] / y; | |
45 | x.y = x.y << z; | |
46 | ``` | |
47 | ||
48 | Examples of **correct** code for this rule with the default `"always"` option: | |
49 | ||
50 | ```js | |
51 | /*eslint operator-assignment: ["error", "always"]*/ | |
52 | ||
53 | x = y; | |
54 | x += y; | |
55 | x = y * z; | |
56 | x = (x * y) * z; | |
57 | x[0] /= y; | |
58 | x[foo()] = x[foo()] % 2; | |
59 | x = y + x; // `+` is not always commutative (e.g. x = "abc") | |
60 | ``` | |
61 | ||
62 | ### never | |
63 | ||
64 | Examples of **incorrect** code for this rule with the `"never"` option: | |
65 | ||
66 | ```js | |
67 | /*eslint operator-assignment: ["error", "never"]*/ | |
68 | ||
69 | x *= y; | |
70 | x ^= (y + z) / foo(); | |
71 | ``` | |
72 | ||
73 | Examples of **correct** code for this rule with the `"never"` option: | |
74 | ||
75 | ```js | |
76 | /*eslint operator-assignment: ["error", "never"]*/ | |
77 | ||
78 | x = x + y; | |
79 | x.y = x.y / a.b; | |
80 | ``` | |
81 | ||
82 | ## When Not To Use It | |
83 | ||
84 | Use 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. |