Assignment in Return Statement

ID

javascript.no_return_assign

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

reliability, suspicious-assignment

Description

Reports return statements whose entire returned value is an assignment expression — return x = 5;, return (x = 5);, return x += 1;, and similar forms. The runtime performs the assignment and returns the assigned value, but the source reads almost identically to a comparison (return x === 5;) and is a frequent typo.

Rationale

  • = and === differ by one character. A reader scanning a return statement expects a comparison there; an assignment is silently incorrect when the author meant to test a value.

  • Even when the assignment is intentional, mixing the side effect into the return value hides it. Splitting it into a separate statement makes the data flow obvious to reviewers and to anyone debugging the function later.

  • Parenthesised forms such as return (x = 5); add no clarity — they still look like a comparison at a glance. This detector flags both the bare and parenthesised forms.

// Bad
function findIndex(arr, target) {
  let i;
  return i = arr.indexOf(target); // looks like a comparison; it is an assignment
}

Remediation

Move the assignment to its own statement and return the variable (or the expected boolean) explicitly.

// Good
function findIndex(arr, target) {
  const i = arr.indexOf(target);
  return i;
}

// Also good — comparison, if that was the intent
function isFive(x) {
  return x === 5;
}

An assignment used inside a sub-expression — return foo(x = 5); or return x + (y = 1); — is not flagged. Those forms do not visually resemble a comparison and are sometimes idiomatic for default injection or memoisation.