Master ESLint: Fixing no-return-assign and no-constant-condition Rules
This article explains the ESLint rules no‑return‑assign and no‑constant‑condition, shows why they trigger, provides clear examples of problematic code, and offers practical refactoring techniques to resolve the warnings while keeping JavaScript code clean and intention‑clear.
no-return-assign
ESLint’s no-return-assign rule forbids returning an assignment expression, because such code can be confusing and often indicates a typo.
function foobar(bar) {
return foo = bar + 1;
}The function returns bar + 1, but the author probably intended to return foo === bar + 1. When this rule fires, check the intended behavior and fix it either by separating the assignment and return:
Split into foo = bar + 1 and return foo;
Or change to return foo === bar + 1.
In ES6, arrow functions can also trigger this rule. For example: setTimeout(() => location.href = myUrl, 1000) This arrow function implicitly returns the assignment, matching the no-return-assign pattern. The intended behavior is only the navigation, so rewrite it without an implicit return:
() => {
location.href = myUrl;
}Then the timed call becomes:
setTimeout(() => { location.href = myUrl }, 1000);no-constant-condition
The no-constant-condition rule disallows constant expressions in if, while, or for conditions, such as if (true) {...}. These often appear for three reasons.
Reason 1: Forgotten debug code
During debugging a condition may be temporarily forced true:
if (true || foo === bar) {
// start feature
}If the true || part is not removed before release, the rule flags it.
Reason 2: Temporarily disabling a feature
Developers may write:
if (false && foo === bar) {
// start feature
}Instead, introduce a flag variable:
let flag = false; // temporary disable
if (flag && foo === bar) {
// start feature
}Reason 3: Using while (true) loops
A common pattern is:
while (true) {
// do something
foo++;
if (foo >= bar) break;
}This triggers the rule. It can be rewritten as a clearer do/while or for loop:
do {
// do something
foo++;
} while (foo < bar); for (; foo < bar; foo++) {
// do something
}If a true loop is truly needed, replace it with for (;;) { … } and manage exit conditions manually.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Baixing.com Technical Team
A collection of the Baixing.com tech team's insights and learnings, featuring one weekly technical article worth following.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
