12-JS/TS OOP: Encapsulation In OOP
Tags: javascript, oop, typescript
Published: 2022-11-29 12:06:19

---
title: 12-JS/TS OOP: Encapsulation In OOP
published: true
description: 
series: jstsoop
tags: javascript, oop, typescript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/824v1xr67a2c92acacjt.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## Encapsulation

Encapsulation means `wrapping up` or `hiding` something, in OOP we use it to hide the implementation details of a class from the outside world.

For example, we have a class called `Car`, and this class has a method called `start`, this method will start the car, but we don't want to expose this method to the outside world, we want to hide it, so we can do that by making it a `private` method, so it can only be accessed from inside the class, and not from outside the class.

```ts
class Car {
  private start() {
    console.log('Car started');
  }
}
```

You can think of it as a `privacy` to your class base code, it meant to be hidden from any outsiders, but available only to you.

## When to use Encapsulation?

Let's take couple of real world examples to understand when to use Encapsulation.

## Medicine Capsule

A real world example of `Encaapsulation` is a `Medicine Capsule`, it's a small container that contains a medicine, and it's wrapped up in a plastic, so it can't be seen from the outside, of course you can crack it, but the idea here is that you don't actually see the medicine, just only the plastic part that wraps the medicine.

## ATM Machine

Another example is an `ATM Machine`, it's a machine that you can use to withdraw money, but you can't see the money inside the machine, you can only see the buttons and the screen, and you can only interact with the buttons and the screen, but what does happen inside the machine is hidden from you.

## Programming Example

We can take an example of Encapsulation in programming a `Cart` class, that class has a job to manage the cart items, like adding, appending quantity, deleting and listing cart items.

Assume that you're adding a product to the cart for the first time, you pass the product id, the cart has a method called `add` and receives that product id, now the user clicks again on the `Add to cart` button thus another call to `add` method is needed here to add the same product, but in this case, the product already exists, so the `add` method will not re-add it again but just increase its quantity, let's see how we can do that.

> I'll write the code in `Typescript` but you can use `Javascript` as well but strongly not recommended to use Javascript anymore in your life, we are about to be in 2023 man!

```ts
class Cart {
  private items: { [productId: number]: number } = {};

  public add(productId: string) {
    if (this.items[productId]) {
      this.items[productId]++;
    } else {
      this.items[productId] = 1;
    }
  }
}
```

As you can see, we have a private property called `items` that holds the cart items, and we have a public method called `add` that receives the product id, and it will check if the product already exists in the cart, if it does, it will increase its quantity, if not, it will add it to the cart.

So the usage will be like this:

```ts
const cart = new Cart();

cart.add(1);
cart.add(1);
cart.add(2);
cart.add(3);

// now our items list will be: 
// { 1: 2, 2: 1, 3: 1 }
```

The product with id `1` has been added twice, so its quantity is `2`, the product with id `2` has been added once, so its quantity is `1`, and the product with id `3` has been added once, so its quantity is `1`.

So we can conclude that we don't really know what is happening here or how the `add` method works internally, but we know it creates or append the quantity, that's all what we need to know, and that's the idea of `Encapsulation`.

## 🎨 Conclusion

In this article, we learned about `Encapsulation` in OOP, and we saw some real world examples of it, and we saw how we can use it in our code.

This concept is very important in OOP, and it's one of the pillars of OOP, so you should know it well and most importantly, you should use it in your code.

## ☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may [buy me a coffee](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/uBh98KZGGF) to get help and support.

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)