]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-return-assign.md
first commit
[pve-eslint.git] / eslint / docs / rules / no-return-assign.md
1 # Disallow Assignment in return Statement (no-return-assign)
2
3 One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a `return` statement. For example:
4
5 ```js
6 function doSomething() {
7 return foo = bar + 2;
8 }
9 ```
10
11 It is difficult to tell the intent of the `return` statement here. It's possible that the function is meant to return the result of `bar + 2`, but then why is it assigning to `foo`? It's also possible that the intent was to use a comparison operator such as `==` and that this code is an error.
12
13 Because of this ambiguity, it's considered a best practice to not use assignment in `return` statements.
14
15 ## Rule Details
16
17 This rule aims to eliminate assignments from `return` statements. As such, it will warn whenever an assignment is found as part of `return`.
18
19 ## Options
20
21 The rule takes one option, a string, which must contain one of the following values:
22
23 * `except-parens` (default): Disallow assignments unless they are enclosed in parentheses.
24 * `always`: Disallow all assignments.
25
26 ### except-parens
27
28 This is the default option.
29 It disallows assignments unless they are enclosed in parentheses.
30
31 Examples of **incorrect** code for the default `"except-parens"` option:
32
33 ```js
34 /*eslint no-return-assign: "error"*/
35
36 function doSomething() {
37 return foo = bar + 2;
38 }
39
40 function doSomething() {
41 return foo += 2;
42 }
43 ```
44
45 Examples of **correct** code for the default `"except-parens"` option:
46
47 ```js
48 /*eslint no-return-assign: "error"*/
49
50 function doSomething() {
51 return foo == bar + 2;
52 }
53
54 function doSomething() {
55 return foo === bar + 2;
56 }
57
58 function doSomething() {
59 return (foo = bar + 2);
60 }
61 ```
62
63 ### always
64
65 This option disallows all assignments in `return` statements.
66 All assignments are treated as problems.
67
68 Examples of **incorrect** code for the `"always"` option:
69
70 ```js
71 /*eslint no-return-assign: ["error", "always"]*/
72
73 function doSomething() {
74 return foo = bar + 2;
75 }
76
77 function doSomething() {
78 return foo += 2;
79 }
80
81 function doSomething() {
82 return (foo = bar + 2);
83 }
84 ```
85
86 Examples of **correct** code for the `"always"` option:
87
88 ```js
89 /*eslint no-return-assign: ["error", "always"]*/
90
91 function doSomething() {
92 return foo == bar + 2;
93 }
94
95 function doSomething() {
96 return foo === bar + 2;
97 }
98 ```
99
100 ## When Not To Use It
101
102 If you want to allow the use of assignment operators in a `return` statement, then you can safely disable this rule.