]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # Disallow Use of Chained Assignment Expressions (no-multi-assign) |
2 | ||
3 | Chaining the assignment of variables can lead to unexpected results and be difficult to read. | |
4 | ||
5 | ```js | |
6 | (function() { | |
7 | const foo = bar = 0; // Did you mean `foo = bar == 0`? | |
8 | bar = 1; // This will not fail since `bar` is not constant. | |
9 | })(); | |
10 | console.log(bar); // This will output 1 since `bar` is not scoped. | |
11 | ``` | |
12 | ||
13 | ## Rule Details | |
14 | ||
15 | This rule disallows using multiple assignments within a single statement. | |
16 | ||
17 | Examples of **incorrect** code for this rule: | |
18 | ||
19 | ```js | |
20 | /*eslint no-multi-assign: "error"*/ | |
21 | ||
22 | var a = b = c = 5; | |
23 | ||
24 | const foo = bar = "baz"; | |
25 | ||
26 | let a = | |
27 | b = | |
28 | c; | |
609c276f TL |
29 | |
30 | class Foo { | |
31 | a = b = 10; | |
32 | } | |
33 | ||
34 | a = b = "quux"; | |
eb39fafa DC |
35 | ``` |
36 | ||
37 | Examples of **correct** code for this rule: | |
38 | ||
39 | ```js | |
40 | /*eslint no-multi-assign: "error"*/ | |
609c276f | 41 | |
eb39fafa DC |
42 | var a = 5; |
43 | var b = 5; | |
44 | var c = 5; | |
45 | ||
46 | const foo = "baz"; | |
47 | const bar = "baz"; | |
48 | ||
49 | let a = c; | |
50 | let b = c; | |
609c276f TL |
51 | |
52 | class Foo { | |
53 | a = 10; | |
54 | b = 10; | |
55 | } | |
56 | ||
57 | a = "quux"; | |
58 | b = "quux"; | |
eb39fafa DC |
59 | ``` |
60 | ||
5422a9cc TL |
61 | ## Options |
62 | ||
63 | This rule has an object option: | |
64 | ||
609c276f | 65 | * `"ignoreNonDeclaration"`: When set to `true`, the rule allows chains that don't include initializing a variable in a declaration or initializing a class field. Default is `false`. |
5422a9cc TL |
66 | |
67 | ### ignoreNonDeclaration | |
68 | ||
69 | Examples of **correct** code for the `{ "ignoreNonDeclaration": true }` option: | |
70 | ||
71 | ```js | |
72 | /*eslint no-multi-assign: ["error", { "ignoreNonDeclaration": true }]*/ | |
73 | ||
74 | let a; | |
75 | let b; | |
76 | a = b = "baz"; | |
77 | ||
78 | const x = {}; | |
79 | const y = {}; | |
80 | x.one = y.one = 1; | |
81 | ``` | |
82 | ||
83 | Examples of **incorrect** code for the `{ "ignoreNonDeclaration": true }` option: | |
84 | ||
85 | ```js | |
86 | /*eslint no-multi-assign: ["error", { "ignoreNonDeclaration": true }]*/ | |
87 | ||
88 | let a = b = "baz"; | |
89 | ||
90 | const foo = bar = 1; | |
609c276f TL |
91 | |
92 | class Foo { | |
93 | a = b = 10; | |
94 | } | |
5422a9cc TL |
95 | ``` |
96 | ||
eb39fafa DC |
97 | ## Related Rules |
98 | ||
99 | * [max-statements-per-line](max-statements-per-line.md) |