Getter Must Return a Value

ID

javascript.getter_return

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

reliability, suspicious-control-flow

Description

Reports a property getter that does not return a value. Two failure modes are flagged:

  • The getter contains no return statement (and does not always throw). Reading the property yields undefined.

  • The getter contains a bare return; statement (no expression). That path also yields undefined and almost always indicates a missed early-exit value.

Both class-body getters (class { get x() {…} }) and object-literal getters ({ get x() {…} }) are checked. Property-descriptor accessors registered through Object.defineProperty are out of scope (no syntactic anchor — those need separate handling).

Rationale

  • A getter is invoked whenever the property is read. Callers cannot tell from the call site that they are running a function — they expect a value. Returning nothing (silently producing undefined) breaks downstream .length, .toString(), equality and so on at unpredictable points.

  • A getter that always throws is allowed because the throw is itself a clear contract — "this property is forbidden". A getter that sometimes returns and sometimes does not is the dangerous case, and the bare return; form is the most common offender.

// Bad
class User {
  get fullName() {                  // forgot to return
    `${this.first} ${this.last}`;
  }
}
new User().fullName === undefined;  // breaks downstream

Remediation

Add an explicit return of the value the getter is meant to produce, or rewrite the getter to throw when no value is appropriate.

// Good
class User {
  get fullName() {
    return `${this.first} ${this.last}`;
  }
}