]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/operator-assignment.md
first commit
[pve-eslint.git] / eslint / docs / rules / operator-assignment.md
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
13 x <<= y | x = x << y
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 ```
20
21 ## Rule Details
22
23 This rule requires or disallows assignment operator shorthand where possible.
24
25 ## Options
26
27 This rule has a single string option:
28
29 * `"always"` (default) requires assignment operator shorthand where possible
30 * `"never"` disallows assignment operator shorthand
31
32 ### always
33
34 Examples of **incorrect** code for this rule with the default `"always"` option:
35
36 ```js
37 /*eslint operator-assignment: ["error", "always"]*/
38
39 x = x + y;
40 x = y * x;
41 x[0] = x[0] / y;
42 x.y = x.y << z;
43 ```
44
45 Examples of **correct** code for this rule with the default `"always"` option:
46
47 ```js
48 /*eslint operator-assignment: ["error", "always"]*/
49
50 x = y;
51 x += y;
52 x = y * z;
53 x = (x * y) * z;
54 x[0] /= y;
55 x[foo()] = x[foo()] % 2;
56 x = y + x; // `+` is not always commutative (e.g. x = "abc")
57 ```
58
59 ### never
60
61 Examples of **incorrect** code for this rule with the `"never"` option:
62
63 ```js
64 /*eslint operator-assignment: ["error", "never"]*/
65
66 x *= y;
67 x ^= (y + z) / foo();
68 ```
69
70 Examples of **correct** code for this rule with the `"never"` option:
71
72 ```js
73 /*eslint operator-assignment: ["error", "never"]*/
74
75 x = x + y;
76 x.y = x.y / a.b;
77 ```
78
79 ## When Not To Use It
80
81 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.