DEV Community

Cover image for Understanding Encapsulation in JavaScript
henry messiah tmt
henry messiah tmt

Posted on

Understanding Encapsulation in JavaScript

introduction

Have you ever wondered why an ATM never shows you its inner workings, yet always gives you just the right amount of money when you press a button? Or why your favorite apps protect your passwords without ever exposing them? Behind these everyday experiences lies a powerful programming principle called Encapsulation.

In JavaScript, encapsulation is the art of hiding the messy details of how something works and exposing only what you need to use. It’s like driving a car—you don’t have to know how the engine combusts fuel, you just press the accelerator and the car moves. Encapsulation makes our code safer, cleaner, and easier to work with, while giving us full control over how data is accessed and modified.

Documenting encapsulation is important because it helps developers understand how to properly structure applications, protect data, and avoid coding mistakes that lead to bugs and security flaws. With the guide from this documentation, you and your team can build reliable software that scales well and remains easy to maintain.

What is Encapsulation?

Encapsulation in JavaScript is one of the core principles of Object-Oriented Programming (OOP).
It means bundling related data (properties/variables) and behavior (methods/functions) into a single unit (object or class) while restricting direct access to some parts of that object.

Encapsulation in simple terms means keeping data and methods together in one unit while restricting direct access to some details. You show only what is needed. You hide the rest.

Why Use Encapsulation?

Protects data from unsafe changes.

Gives controlled access through getters and setters.

Keeps code organized and reusable.

Provides better security for sensitive logic.

Examples of encapsulation in JavaScript

  1. Using Objects
const user = {
  name: "Henry",
  age: 36,

  getAge() {
    return this.age;
  },

  setAge(newAge) {
    if (newAge > 0) {
      this.age = newAge;
    } else {
      console.log("Invalid age");
    }
  }
};

console.log(user.getAge()); // 36
user.setAge(40);
console.log(user.getAge()); // 40
Enter fullscreen mode Exit fullscreen mode

Here, age is managed only through getAge and setAge.

  1. Using Classes with Private Fields
class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.#balance) {
      this.#balance -= amount;
    } else {
      console.log("Insufficient funds");
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(1000);
account.withdraw(300);
console.log(account.getBalance()); // 700
Enter fullscreen mode Exit fullscreen mode

The field #balance is private and cannot be accessed from outside.

  1. Using Closures
function Car() {
  let engineOn = false;

  return {
    startEngine: () => {
      engineOn = true;
      console.log("Engine started");
    },
    stopEngine: () => {
      engineOn = false;
      console.log("Engine stopped");
    },
    drive: () => {
      if (engineOn) {
        console.log("Car is moving");
      } else {
        console.log("Start the engine first");
      }
    }
  };
}

const myCar = Car();
myCar.drive();       // Start the engine first
myCar.startEngine(); // Engine started
myCar.drive();       // Car is moving
Enter fullscreen mode Exit fullscreen mode

The variable engineOn is private to the function.

Real World Examples

ATM Machine

class ATM {
  #balance;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
      console.log(`Deposited: ₦${amount}`);
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.#balance) {
      this.#balance -= amount;
      console.log(`Withdrawn: ₦${amount}`);
    } else {
      console.log("Insufficient funds");
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const myATM = new ATM(1000);
myATM.deposit(500);
myATM.withdraw(300);
console.log("Balance:", myATM.getBalance()); // 1200
Enter fullscreen mode Exit fullscreen mode

The balance is private. You only interact through deposit, withdraw, and getBalance.

Password Manager

function PasswordManager() {
  let passwords = {};

  return {
    addPassword: (site, pwd) => {
      passwords[site] = pwd;
    },
    getPassword: (site) => {
      return passwords[site] ? "****" : "No password saved";
    },
    verifyPassword: (site, pwd) => {
      return passwords[site] === pwd;
    }
  };
}

const manager = PasswordManager();
manager.addPassword("gmail", "mySecret123");
console.log(manager.getPassword("gmail")); // ****
console.log(manager.verifyPassword("gmail", "mySecret123")); // true
Enter fullscreen mode Exit fullscreen mode

The stored passwords are hidden and safe from direct access.

Car

class Car {
  #engineStatus = false;

  startEngine() {
    this.#engineStatus = true;
    console.log("Engine started");
  }

  stopEngine() {
    this.#engineStatus = false;
    console.log("Engine stopped");
  }

  drive() {
    if (this.#engineStatus) {
      console.log("Car is moving");
    } else {
      console.log("Start the engine first");
    }
  }
}

const myCar = new Car();
myCar.drive();       
myCar.startEngine(); 
myCar.drive();       
Enter fullscreen mode Exit fullscreen mode

The engine status is hidden. The driver interacts only with exposed methods.

Conclusions

Encapsulation means hiding internal details.

It gives controlled access through methods.

It keeps data safe and code maintainable.

Real-world parallels include ATMs, password managers, and cars.

Top comments (24)

Collapse
 
adika_david_f4882f8904c91 profile image
ADIKA DAVID

This is a very insightful article on encapsulation in JavaScript. I appreciate the way you clearly explained the concept and highlighted its importance in writing clean, maintainable, and secure code. Encapsulation is often overlooked, but as you rightly pointed out, it plays a vital role in protecting data and ensuring proper abstraction. The practical examples you provided make the topic much easier to grasp, even for those who may not have encountered it before. Well done on simplifying such an important concept and presenting it in a relatable way. Looking forward to reading more of your work on core programming principles

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Well appreciated. Bless up.

Collapse
 
richard_ben_2ca6ff6b3c8ac profile image
Richard Ben

Thank you very much

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Welcome Richard.

Collapse
 
charles_nwachukwu_5370f00 profile image
Charles Nwachukwu • Edited

Thank you for your simplified explanations as always. Topics like these are easily overlooked due to its presumed complexity but you make it so easy to comprehend and I look forward to learning more from you.

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thank you very much Charles.

Collapse
 
justin_ikakah_4fe4f968621 profile image
Justin Ikakah

Great work as always

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thank you Mr. Justin. Bless up.

Collapse
 
tamsjazz profile image
Tams Berry

Great read. The most comprehensible article on encapsulation I’ve read. Well done.

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thanks man, Bless up.

Collapse
 
richard_ben_2ca6ff6b3c8ac profile image
Richard Ben

The simplicity in the write up is exceptional. Thank you very much for sharing.

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thanks.

Collapse
 
meli_henry_173c75d17fa37b profile image
Meli Henry

Fast becoming my favourite writer, keeps things simple yet understandable

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thanks for your nice words.

Collapse
 
dagogoathan profile image
Dagogo Jaja

Great article. Your clear examples made encapsulation in JavaScript easy to understand.

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thank you sir.

Collapse
 
alexander_ogbu_e55ffed921 profile image
Alexander Ogbu

Great write-up. 👍👍

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

God bless you.

Collapse
 
stanley_agbam_9b514e55e7c profile image
Stanley Agbam

This is so easy to read and understand, even to a novice. Great job.

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thanks man. Bless up.

Collapse
 
ebiweni_lokoja_f8e97af1f5 profile image
EBIWENI LOKOJA

I have heard of encapsulation in JavaScript before, never read it this good.

Thank you for expanding my knowledge

Collapse
 
henry_messiahtmt_099ca84 profile image
henry messiah tmt

Thanks.