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 causesnew MyClass(…)to evaluate toobjinstead of an instance ofMyClass. Code that relies oninstanceof MyClassor 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;
}
}