Home Projects Portfolio Dashboard Export PDF Log in
JavaScript

Implementing Private Properties: A Modern Approach to Data Encapsulation in JavaScript

In object-oriented JavaScript, the struggle to keep data truly internal is a classic challenge. We often rely on naming conventions like underscores, but those don't stop external modification. Working on ejemplo_presupuesto, I recently shifted our user model to use modern, native private properties for better state management.

The Problem with Public State

Previously, our user data objects had properties that were easily accessible and mutable from anywhere in the application. This led to unpredictable side effects, where external functions could inadvertently modify a user's internal state, breaking our budget calculations.

class User {
  constructor(name) {
    this._name = name; // Convention only, still public
  }
}

Moving to Private Class Fields

By adopting ECMAScript's private class features, we can enforce strict boundaries. Any property prefixed with a # is now truly private to the class instance. Attempting to access these from outside the class results in a syntax error, effectively protecting our data integrity.

class User {
  #name;

  constructor(name) {
    this.#name = name;
  }

  getName() {
    return this.#name;
  }
}

const user = new User('Alice');
console.log(user.getName()); // Works
console.log(user.#name);     // Syntax Error

Architectural Benefits

Transitioning to this pattern provided two immediate benefits:

  1. Encapsulation: The internal representation of a user is now hidden from the rest of the application.
  2. Predictability: We now use controlled methods (getters and setters) to interact with sensitive data, making it easier to debug state changes.

The Takeaway

Stop relying on naming conventions to signal privacy. If you are working in a modern JavaScript environment, migrate your internal state to use private class fields (#). It simplifies your API surface and prevents bugs caused by accidental state mutation. Start by refactoring one class in your domain layer today.


Generated with Gitvlg.com

Implementing Private Properties: A Modern Approach to Data Encapsulation in JavaScript
I

Ivana Castillo

Author

Share: