11 In conditional statements, it is very easy to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`). For example:
14 // Check the user's job title
15 if (user.jobTitle = "manager") {
16 // user.jobTitle is now incorrect
20 There are valid reasons to use assignment operators in conditional statements. However, it can be difficult to tell whether a specific assignment was intentional.
24 This rule disallows ambiguous assignment operators in test conditions of `if`, `for`, `while`, and `do...while` statements.
28 This rule has a string option:
30 * `"except-parens"` (default) allows assignments in test conditions *only if* they are enclosed in parentheses (for example, to allow reassigning a variable in the test of a `while` or `do...while` loop)
31 * `"always"` disallows all assignments in test conditions
35 Examples of **incorrect** code for this rule with the default `"except-parens"` option:
40 /*eslint no-cond-assign: "error"*/
42 // Unintentional assignment
48 // Practical example that is similar to an error
49 function setHeight(someNode) {
52 someNode.height = "100px";
53 } while (someNode = someNode.parentNode);
59 Examples of **correct** code for this rule with the default `"except-parens"` option:
64 /*eslint no-cond-assign: "error"*/
66 // Assignment replaced by comparison
72 // Practical example that wraps the assignment in parentheses
73 function setHeight(someNode) {
76 someNode.height = "100px";
77 } while ((someNode = someNode.parentNode));
80 // Practical example that wraps the assignment and tests for 'null'
81 function setHeight(someNode) {
84 someNode.height = "100px";
85 } while ((someNode = someNode.parentNode) !== null);
93 Examples of **incorrect** code for this rule with the `"always"` option:
98 /*eslint no-cond-assign: ["error", "always"]*/
100 // Unintentional assignment
106 // Practical example that is similar to an error
107 function setHeight(someNode) {
110 someNode.height = "100px";
111 } while (someNode = someNode.parentNode);
114 // Practical example that wraps the assignment in parentheses
115 function setHeight(someNode) {
118 someNode.height = "100px";
119 } while ((someNode = someNode.parentNode));
122 // Practical example that wraps the assignment and tests for 'null'
123 function setHeight(someNode) {
126 someNode.height = "100px";
127 } while ((someNode = someNode.parentNode) !== null);
133 Examples of **correct** code for this rule with the `"always"` option:
138 /*eslint no-cond-assign: ["error", "always"]*/
140 // Assignment replaced by comparison