Returning a private array directly

Returning a private array directly

Description

If a public method returns its private array directly, callers can modify the object's internal state through that reference.

Potential impact

  • External code may change role lists, policies, or validated values.
  • The object's invariants may be bypassed.

Remediation

  • Return a copy using spread syntax, slice(), or Array.from().
  • Expose immutable data structures when callers do not need to modify values.
  • A shallow copy still shares nested objects. Copy mutable elements to the required depth or make them immutable.

Examples

Before

javascript
class AccessPolicy {
  #roles = [];

  getRoles() {
    return this.#roles;
  }
}

After

javascript
class AccessPolicy {
  #roles = [];

  getRoles() {
    return [...this.#roles];
  }
}

Explanation:

  • Before: Callers can change the private array through the returned reference.
  • After: Returning a copy separates the array itself from the caller's changes.

References