Encapsulation in Javascript

Vikash Gupta
2 min readSep 10, 2020

Even though Javascript is not a true object oriented language there are 2 popular features to enable encapsulation in Javascript.

Encapsulation refers to the bundling of data with the methods that operate on that data

  • Closure
  • Classes

1. Using closure

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

Sample

function Counter() {
var count = 0;
function increment() {
count +=1;
}
function getCount() {
return count;
}
return {
increment:increment,
getCount:getCount
};
}
Usage:
const myCounter = Counter();
myCounter.increment();console.log(
myCounter.getCount()
);`

2. Using Classes

Classes introduced in ES6. Classes are a template for creating objects. They encapsulate data with code to work on that data.

Sample

class Counter {
count = 0

increment () {
this.count += 1;
}
getCount () {
return this.count
}
}
Usage:const myCounter = new Counter();
myCounter.increment();
console.log(
myCounter.getCount()
);

Conclusion

Closures don’t have to worry about the context that this is referring to hence offer simplicity.

Meanwhile, classes tend to be slightly more performant if we are going to be creating multiple instances of an object.

If we are creating multiple instances of an object, classes will best suit our needs. Meanwhile, if we don’t plan to create multiple instances, the simplicity of closures may be a better fit for our project.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response