1 # Disallow Assignment in return Statement (no-return-assign)
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:
6 function doSomething() {
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.
13 Because of this ambiguity, it's considered a best practice to not use assignment in `return` statements.
17 This rule aims to eliminate assignments from `return` statements. As such, it will warn whenever an assignment is found as part of `return`.
21 The rule takes one option, a string, which must contain one of the following values:
23 * `except-parens` (default): Disallow assignments unless they are enclosed in parentheses.
24 * `always`: Disallow all assignments.
28 This is the default option.
29 It disallows assignments unless they are enclosed in parentheses.
31 Examples of **incorrect** code for the default `"except-parens"` option:
34 /*eslint no-return-assign: "error"*/
36 function doSomething() {
40 function doSomething() {
45 Examples of **correct** code for the default `"except-parens"` option:
48 /*eslint no-return-assign: "error"*/
50 function doSomething() {
51 return foo == bar + 2;
54 function doSomething() {
55 return foo === bar + 2;
58 function doSomething() {
59 return (foo = bar + 2);
65 This option disallows all assignments in `return` statements.
66 All assignments are treated as problems.
68 Examples of **incorrect** code for the `"always"` option:
71 /*eslint no-return-assign: ["error", "always"]*/
73 function doSomething() {
77 function doSomething() {
81 function doSomething() {
82 return (foo = bar + 2);
86 Examples of **correct** code for the `"always"` option:
89 /*eslint no-return-assign: ["error", "always"]*/
91 function doSomething() {
92 return foo == bar + 2;
95 function doSomething() {
96 return foo === bar + 2;
100 ## When Not To Use It
102 If you want to allow the use of assignment operators in a `return` statement, then you can safely disable this rule.