Encapsulation
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 17 of 56.
Encapsulation is a process of combining data inside a class within one unit.
This helps to put restrictions on accessing class data directly, eventually helping us to prevent any accidental modification of data.
Let's see encapsulation in action with a simple example. Create a basic object with public properties:
const user = {
name: "John",
email: "john@example.com"
};Anyone can directly access and modify these properties:
user.name = "Jane"; // Easy to modify from outside
console.log(user.email); // Easy to access from outsideA more encapsulated approach uses closures to hide data:
function createUser(name, email) {
// These variables are private (encapsulated)
let userName = name;
let userEmail = email;
// Return an object with methods to interact with the private data
return {
getName: function() {
return userName;
},
getEmail: function() {
return userEmail;
},
setName: function(newName) {
userName = newName;
}
};
}
const encapsulatedUser = createUser("John", "john@example.com");Now, to interact with the data:
console.log(encapsulatedUser.getName()); // "John"
encapsulatedUser.setName("Jane");
console.log(encapsulatedUser.getName()); // "Jane"
// Cannot directly access the data
console.log(encapsulatedUser.userName); // undefinedChallenge
You're given code that uses encapsulation to protect user data. Your task is to add a getAge() method to access the age.
Tests will check:
getAge()method exists- It returns the correct age
- The age info remains private
Expected Output:
john_doe
25
Cheat sheet
Encapsulation is a process of combining data inside a class within one unit and restricting direct access to that data, preventing accidental modification.
Without encapsulation, object properties are publicly accessible:
const user = {
name: "John",
email: "john@example.com"
};
user.name = "Jane"; // Can be modified directly
console.log(user.email); // Can be accessed directlyUsing closures to encapsulate data:
function createUser(name, email) {
// Private variables (encapsulated)
let userName = name;
let userEmail = email;
// Public methods to interact with private data
return {
getName: function() {
return userName;
},
getEmail: function() {
return userEmail;
},
setName: function(newName) {
userName = newName;
}
};
}
const encapsulatedUser = createUser("John", "john@example.com");
console.log(encapsulatedUser.getName()); // "John"
encapsulatedUser.setName("Jane");
console.log(encapsulatedUser.getName()); // "Jane"
console.log(encapsulatedUser.userName); // undefined (private data not accessible)Try it yourself
import { createUser } from './createUser.js';
// Test code - don't modify
const user = createUser("john_doe", 25);
console.log(user.getUsername()); // Should output "john_doe"
console.log(user.getAge()); // Should output 25
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge