How to Have Encapsulation in JavaScript

Cristian Salcescu
Frontend Essentials
2 min readFeb 28, 2021

--

Photo by the author

Encapsulation is about data-hiding. That’s it, we have private data behind public methods working with that data.

The main idea is to expose as little as possible to the outside world. Minimizing the connections with the external environment reduces unexpected changes. What we can hide, we can change.

Let’s look at how to achieve it.

Classes

A new option for achieving encapsulation is to use the hash # symbol to declare a private variable inside a class. This feature is part of ES2020.

It is great that classes will support encapsulation, but there are still some annoying things that we may need to take into consideration.

For example, the this keyword may change context unexpectedly.

setTimeout(counter.increment, 0);//Cannot read private member #count from an object whose class did not declare it at increment

This kind of issue can be usually solved using the arrow syntax but is something to pay attention…

--

--