| Encapsulation | LocalStorage-and-SessionStorage | |
π§ Abstraction Basics in JavaScript |
Definition: Abstraction is the concept of hiding the complex internal implementation details of an object or system and exposing only the essential features that are relevant to the user. It simplifies interaction and promotes cleaner, more maintainable code.
Abstraction is a core principle of object-oriented programming (OOP) that involves hiding complex implementation details and showing only the essential features of an object. Its primary goal is to manage complexity by providing a simplified, high-level interface to the user.
Since JavaScript doesn't have native "abstract" classes like some other languages, developers achieve abstraction using different features.
Functions are the simplest form of abstraction. You can encapsulate a complex set of steps into a reusable function, hiding the internal logic from the user.
function sendEmail(recipient, subject, body) {
// Complex implementation logic:
// - Establish a connection to an email server
// - Authenticate the user
// - Construct the email message with headers
// - Send the message
// - Handle potential network errors
console.log(`Sending email to ${recipient} with subject "${subject}"...`);
// (Hidden logic)
console.log("Email sent successfully!");
}
// User only needs to know what the function does, not how it does it.
sendEmail("test@example.com", "Hello", "How are you?");
Encapsulation is the mechanism that helps implement abstraction. By bundling data and methods together and using private class fields (with the # prefix), you can hide implementation details.
class SmartLight {
#status = "off"; // Private, encapsulated state
#brightness = 0;
constructor() {
console.log("Smart light initialized.");
}
// Public methods expose a simple interface
turnOn() {
this.#status = "on";
this.#brightness = 100;
console.log(`Light is on at ${this.#brightness}% brightness.`);
}
turnOff() {
this.#status = "off";
this.#brightness = 0;
console.log("Light is off.");
}
// A method that uses the private state
getBrightness() {
return this.#brightness;
}
}
const light = new SmartLight();
light.turnOn();
// The user doesn't need to know about the private #status or #brightness.
console.log(light.getBrightness());
// Trying to access a private field directly will cause an error:
// light.#status; // Throws a SyntaxError
The JavaScript module system is another powerful way to achieve abstraction. Any variables or functions that are not explicitly exported are private and hidden from external access.
const PRIVATE_STATE = {
status: "off",
brightness: 0
};
function turnOn() {
PRIVATE_STATE.status = "on";
PRIVATE_STATE.brightness = 100;
console.log(`Light is on at ${PRIVATE_STATE.brightness}% brightness.`);
}
function turnOff() {
PRIVATE_STATE.status = "off";
PRIVATE_STATE.brightness = 0;
console.log("Light is off.");
}
export { turnOn, turnOff };
import { turnOn, turnOff } from './light-module.js';
turnOn(); // Works as expected
// Trying to access the private state will fail
// console.log(PRIVATE_STATE); // ReferenceError
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
getDetails() {
return `${this.name} is ${this.age} years old.`;
}
}
const user1 = new User("Anuj", 30);
console.log(user1.getDetails()); // Output: Anuj is 30 years old.
Note: The internal structure of the User class is hidden from the user. They only interact with the getDetails() method.
#field) to hide data in ES2022+. | Encapsulation | LocalStorage-and-SessionStorage | |