]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # disallow the unary operators `++` and `--` (no-plusplus) |
2 | ||
3 | Because the unary `++` and `--` operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code. | |
4 | ||
5 | ```js | |
6 | var i = 10; | |
7 | var j = 20; | |
8 | ||
9 | i ++ | |
10 | j | |
11 | // i = 11, j = 20 | |
12 | ``` | |
13 | ||
14 | ```js | |
15 | var i = 10; | |
16 | var j = 20; | |
17 | ||
18 | i | |
19 | ++ | |
20 | j | |
21 | // i = 10, j = 21 | |
22 | ``` | |
23 | ||
24 | ## Rule Details | |
25 | ||
26 | This rule disallows the unary operators `++` and `--`. | |
27 | ||
28 | Examples of **incorrect** code for this rule: | |
29 | ||
30 | ```js | |
31 | /*eslint no-plusplus: "error"*/ | |
32 | ||
33 | var foo = 0; | |
34 | foo++; | |
35 | ||
36 | var bar = 42; | |
37 | bar--; | |
38 | ||
39 | for (i = 0; i < l; i++) { | |
40 | return; | |
41 | } | |
42 | ``` | |
43 | ||
44 | Examples of **correct** code for this rule: | |
45 | ||
46 | ```js | |
47 | /*eslint no-plusplus: "error"*/ | |
48 | ||
49 | var foo = 0; | |
50 | foo += 1; | |
51 | ||
52 | var bar = 42; | |
53 | bar -= 1; | |
54 | ||
55 | for (i = 0; i < l; i += 1) { | |
56 | return; | |
57 | } | |
58 | ``` | |
59 | ||
60 | ## Options | |
61 | ||
62 | This rule has an object option. | |
63 | ||
64 | * `"allowForLoopAfterthoughts": true` allows unary operators `++` and `--` in the afterthought (final expression) of a `for` loop. | |
65 | ||
66 | ### allowForLoopAfterthoughts | |
67 | ||
68 | Examples of **correct** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option: | |
69 | ||
70 | ```js | |
71 | /*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/ | |
72 | ||
73 | for (i = 0; i < l; i++) { | |
74 | doSomething(i); | |
75 | } | |
76 | ||
77 | for (i = l; i >= 0; i--) { | |
78 | doSomething(i); | |
79 | } | |
80 | ||
81 | for (i = 0, j = l; i < l; i++, j--) { | |
82 | doSomething(i, j); | |
83 | } | |
84 | ``` | |
85 | ||
86 | Examples of **incorrect** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option: | |
87 | ||
88 | ```js | |
89 | /*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/ | |
90 | ||
91 | for (i = 0; i < l; j = i++) { | |
92 | doSomething(i, j); | |
93 | } | |
94 | ||
95 | for (i = l; i--;) { | |
96 | doSomething(i); | |
97 | } | |
98 | ||
99 | for (i = 0; i < l;) i++; | |
100 | ``` |