On this page

Encapsulation and Private Fields

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Encapsulation is one of the four fundamental pillars of Object-Oriented Programming (OOP). It is the practice of bundling data (properties) and the methods that operate on that data into a single unit, while simultaneously restricting direct access to some of the object's components. In modern JavaScript, this is achieved through Private Fields, denoted by the hash # prefix.

The Concept of Encapsulation​

The primary goal of encapsulation is to hide the internal state of an object and require all interaction to happen through a well-defined interface (public methods). This prevents "external" code from accidentally or intentionally corrupting the internal logic of your object, ensuring that the object remains in a valid state.

Implementing Private Fields with​

Historically, JavaScript developers used an underscore prefix (e.g., _password) as a convention to signal that a property was intended to be private. However, this was merely a "gentleman's agreement" and did not provide actual technical protection.

The introduction of Private Class Fields (using the # symbol) provides true, engine-level privacy. When a property name starts with #, it is completely inaccessible from outside the class.

Syntax and Declaration​

Private fields must be declared at the top level of the class body before they are used. They cannot be created dynamically on the fly.


class BankAccount {

  // Declaring a private field

  #balance;



  constructor(initialDeposit) {

    this.#balance = initialDeposit;

  }



  getBalance() {

    return `Your balance is $${this.#balance}`;

  }

}



const myAccount = new BankAccount(1000);



console.log(myAccount.getBalance()); // Output: Your balance is $1000

// console.log(myAccount.#balance);  // Syntax Error: Private field '#balance' must be declared in an enclosing class

Controlled Access with Getters and Setters​

To allow external code to interact with private data safely, we use Getters and Setters. These are special methods that look like properties but allow you to execute logic during the reading or writing process.


class User {

  #age;



  constructor(age) {

    this.#age = age;

  }



  // Getter

  get age() {

    return `${this.#age} years old`;

  }



  // Setter with validation logic

  set age(newValue) {

    if (newValue > 0 && newValue < 120) {

      this.#age = newValue;

    } else {

      console.error("Invalid age provided.");

    }

  }

}



const person = new User(25);

person.age = 30; // Calls the setter

console.log(person.age); // Calls the getter: "30 years old"

Private Methods​

Just as data can be private, logic can also be hidden. If a class has a complex internal process that should not be exposed to the user of the class, you can define a Private Method using the same # prefix.


class SecureSystem {

  #generateKey() {

    return Math.random().toString(36).substring(2);

  }



  getAccess() {

    const key = this.#generateKey(); // Internal logic is hidden

    console.log(`Access granted with key: ${key}`);

  }

}



const sys = new SecureSystem();

sys.getAccess();

// sys.#generateKey(); // Error: Method is private

Benefits of Encapsulation​

  1. Data Integrity: By using setters, you can validate data before it is saved, preventing "impossible" states (like a negative bank balance).
  2. Simplified Interface: Users of your class only see the methods they need, reducing the complexity of the API.
  3. Future-Proofing: You can change the internal implementation (e.g., changing how #balance is calculated) without breaking any external code that relies on the public getBalance() method.

Professional Rules for Privacy​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Classes

Next

Core Objects