Encapsulation in JavaScript – What Is Encapsulation?
Encapsulation is an object’s design pattern that prevents external code from interacting with internal data (properties). Instead, external code would use methods to operate on the object’s internal implementations.
The encapsulation concept is like a capsule whose shell prevents users from directly accessing the enclosed medicine.
In other words, you encapsulate an object’s data when you make them private and provide publicly available methods for users to operate on the private data.
How Does Encapsulation Work in JavaScript?
Consider the following code:
The snippet above encapsulated Name
’s data because it defined myName
as a private feature and provided two public methods for users to read and update the class’s internal implementation.
Consequently, the bio
instance object knows nothing about the class’s internal data and cannot interact with it directly.
How to Access Encapsulated Data in JavaScript
Whenever users need to access encapsulated data, they would use publicly available methods like so:
Now that we know how encapsulation works in JavaScript and how to access encapsulated data, we can discuss its benefits.
What Is the Benefit of Encapsulation in JavaScript?
Encapsulation keeps your object clean and prevents minor internal refactoring from breaking the user’s code.
For instance, consider the following code:
Since the snippet above did not encapsulate the class’s data, refactoring the class field’s name would break users’ code.
Here’s an example:
The snippet above returned undefined
because refactoring the class’s internal implementation broke the user’s bio.myName
code. For the application to work appropriately, the user must update every instance of the code (which can be burdensome for large projects).
However, encapsulation prevents such refactoring from breaking the user’s code.
Here’s an example:
You can see that refactoring the class’s internal implementation did not break the user’s code. That’s the beauty of encapsulation!
Encapsulation allows you to provide users with an interface independent of the object’s underlying data. Therefore, you minimize the likelihood of users’ code breaking when you alter internal implementations.