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