JavaScript Encapsulation

Introduction to JavaScript Encapsulation

JavaScript encapsulation is a fundamental concept in object-oriented programming (OOP) that allows for the organization and protection of data and methods within a class. Encapsulation ensures that the internal workings of an object are hidden from the outside world, promoting data integrity and security.

In JavaScript, encapsulation is achieved through the use of classes, objects, and access modifiers. Let’s explore these concepts further with some examples.

Example 1: Encapsulating Data with Getters and Setters

Consider a simple class called Person that represents a person’s information, such as their name and age. We can encapsulate these properties using getters and setters.


class Person {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }

  get name() {
    return this._name;
  }

  set name(newName) {
    this._name = newName;
  }

  get age() {
    return this._age;
  }

  set age(newAge) {
    if (newAge >= 0) {
      this._age = newAge;
    }
  }
}

const john = new Person("John Doe", 25);
console.log(john.name); // Output: John Doe
john.name = "John Smith";
console.log(john.name); // Output: John Smith
john.age = -5; // Age cannot be negative
console.log(john.age); // Output: 25

In this example, the properties _name and _age are encapsulated within the Person class. The getters and setters allow controlled access to these properties, ensuring that valid values are set and retrieved.

Example 2: Encapsulating Methods

Encapsulation is not limited to data properties; it also applies to methods. Let’s consider a class called Calculator that encapsulates arithmetic operations.


class Calculator {
  add(a, b) {
    return a + b;
  }

  subtract(a, b) {
    return a - b;
  }

  multiply(a, b) {
    return a * b;
  }

  divide(a, b) {
    if (b !== 0) {
      return a / b;
    }
    return "Cannot divide by zero.";
  }
}

const calc = new Calculator();
console.log(calc.add(5, 3)); // Output: 8
console.log(calc.subtract(10, 4)); // Output: 6
console.log(calc.multiply(2, 6)); // Output: 12
console.log(calc.divide(10, 2)); // Output: 5
console.log(calc.divide(7, 0)); // Output: Cannot divide by zero.

In this example, the methods add, subtract, multiply, and divide are encapsulated within the Calculator class. These methods can only be accessed through an instance of the class, promoting encapsulation and code organization.

Example 3: Private Properties and Methods

JavaScript does not have built-in support for private properties and methods, but we can simulate them using closures and the concept of lexical scoping.


function Counter() {
  let count = 0;

  function increment() {
    count++;
  }

  function decrement() {
    count--;
  }

  function getCount() {
    return count;
  }

  return {
    increment,
    decrement,
    getCount
  };
}

const counter = Counter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // Output: 2
counter.decrement();
console.log(counter.getCount()); // Output: 1

In this example, the count variable and the functions increment, decrement, and getCount are encapsulated within the Counter function. These properties and methods are not accessible from outside the function, providing a form of privacy.

Conclusion

JavaScript encapsulation is a powerful concept that allows for the organization, protection, and control of data and methods within classes. By using getters, setters, and access modifiers, we can ensure the integrity and security of our code. Additionally, we can simulate private properties and methods using closures and lexical scoping. Understanding and applying encapsulation in JavaScript leads to cleaner, more maintainable code.

Remember, encapsulation is just one of the principles of OOP. It is essential to combine it with other principles like inheritance and polymorphism to fully leverage the benefits of object-oriented programming.

Scroll to Top