What Is Encapsulation?

Encapsulation is one of the fundamental principles of Object-Oriented Programming.

Its main purpose is to protect an object’s internal data and implementation details by preventing direct access from outside the class.

Instead of allowing external code to modify everything freely, the object controls how its own data is accessed and updated.

Why Do We Use Encapsulation?

Imagine a car factory.

Customers can see and use the finished car, but they cannot see the factory’s internal production process, financial records, or manufacturing details.

Those details belong to the factory and are hidden from the outside world.

Objects work the same way.

Some data and methods are intended for internal use only, so they should not be accessible from outside the class.

These members are called private members.

Making a Property Private

In JavaScript, a property becomes private by prefixing its name with #.

class Car {
#profit = 0;
constructor(price) {
this.#profit += price;
}
}
const car = new Car(10000);
console.log(car.#profit); // SyntaxError

Here, #profit is a private property.

It can be accessed only from inside the class. Attempting to access it from outside results in a syntax error.

Making Methods Private

Methods can also be private.

class Car {
#profit = 0;
constructor(price) {
this.#profit += price;
this.#printProfit();
}
#printProfit() {
console.log(this.#profit);
}
}
const car = new Car(10000);
car.#printProfit(); // SyntaxError

The method #printProfit() is private.

It can be called from within the class but cannot be accessed from outside.

When Should You Use Private Members?

Private properties and methods are useful when they are part of the object’s internal implementation and should not be exposed to other parts of the program.

Encapsulation helps you:

  • Protect data from unintended modifications.
  • Hide implementation details.
  • Reduce bugs caused by incorrect usage.
  • Keep the object responsible for managing its own state.

Key Takeaways

  • Encapsulation hides an object’s internal implementation and protects its data.
  • Prefix a property or method with # to make it private in JavaScript.
  • Private members are accessible only inside the class.
  • Use private members to hide implementation details that external code doesn’t need to know about.