Return Value from Constructor

ID

javascript.no_constructor_return

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

best-practice, reliability

Description

Reports return <value>; statements inside a class constructor. JavaScript constructors implicitly return the newly-constructed this; explicitly returning an object replaces that, and explicitly returning a primitive is silently ignored — both forms surprise readers. A bare return; is allowed because it is just an early exit and does not affect the constructed object.

Rationale

  • return obj; from a constructor causes new MyClass(…​) to evaluate to obj instead of an instance of MyClass. Code that relies on instanceof MyClass or on the prototype chain breaks silently.

  • return primitive; is ignored at runtime — the developer who wrote it likely expected a different effect.

  • Even return this; is unnecessary noise and confuses readers about whether the author intended a different semantic.

// Bad
class Cache {
  constructor(key) {
    if (cache.has(key)) {
      return cache.get(key);   // breaks `new Cache(...) instanceof Cache`
    }
    this.key = key;
  }
}

Remediation

Use early-return; (no value) for guard clauses, or refactor the "return existing object" pattern into a static factory method.

// Good
class Cache {
  constructor(key) {
    this.key = key;
  }

  static get(key) {
    return cache.get(key) ?? new Cache(key);
  }
}