Encapsulation Explained using JavaScript
Tags: javascript, oop, programming, coding
Published: 2023-04-15 01:15:21

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that refers to the concept of binding the data (member variable) and the methods that operate on the data (member functions) within a single unit called a class.

Encapsulation enables programmers to hide the implementation details of one object from other objects and restrict direct access to the internal state of an object.



Encapsulation provides several benefits, such as:

-  improving the maintainability of the code -- making it easier to modify and extend the class's functionality.

- Enhancing the security of the data by preventing unauthorized access. 

- It also allows the programmer to use the class's interface without knowing the implementation details, which makes it easier to use and understand.

let look at an example of encapsulation in JavaScript:

```
function createCounter() {
  let count = 0;

  function increment() {
    count++;
    console.log(count);
  }

  return increment;
}

const counter = createCounter();

counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3


```

In this example, we have a `createCounter` function that returns an `increment` function. The `increment` function has access to the `count` variable through a closure, but the count variable is not accessible from outside the function. The only way to modify the `count` variable is by calling the `increment` function, which increments the count and logs it to the console.
This is an example of encapsulation because the `count` variable is hidden from the outside world and can only be accessed through the `increment` function, which provides a well-defined interface for accessing and modifying the count.

In addition to using closures, another way to achieve encapsulation in JavaScript is by using `setters` and `getters`. `Setters` and `getters` are methods that allow us to control how properties are set and retrieved from an object.

Here's an example of encapsulation using `setters` and `getters`:


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

  get name() {
    return this._name;
  }

  set name(newName) {
    if (typeof newName === "string") {
      this._name = newName;
    } else {
      throw new Error("Name must be a string");
    }
  }

  get age() {
    return this._age;
  }

  set age(newAge) {
    if (typeof newAge === "number" && newAge > 0) {
      this._age = newAge;
    } else {
      throw new Error("Age must be a positive number");
    }
  }
}

const person = new Person("John Doe", 30);
console.log(person.name); // Output: John Doe
console.log(person.age); // Output: 30

person.name = "Jane Doe";
person.age = 25;

console.log(person.name); // Output: Jane Doe
console.log(person.age); // Output: 25

person.name = 123; // Throws an error: Name must be a string
person.age = -1; // Throws an error: Age must be a positive number

```

In this example, we have a Person class with name and age properties that are encapsulated using `setters` and` getters`. The `getters` allow us to retrieve the values of these properties, while the `setters` allow us to control how they are set.

For instance, the name setter checks whether the new value is a string before setting the _name property, while the age setter checks whether the new value is a positive number. This allows us to enforce certain constraints on the values of these properties and ensure that they are always valid.

By encapsulating the` name` and `age` properties using `setters` and `getters`, we can hide their internal implementation and control how they are accessed and modified from outside the class. This helps to maintain the integrity of the object and prevent any unexpected side-effects that could result from direct manipulation of its properties.

In Summary, In encapsulation can be achieved through the use of closures and modules, as well as using `setters` and `getters` to control how properties are set and retrieved from an object. it also helps to improve the quality and maintainability of software systems.