Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Encapsulation using Anonymous Functions
Object-oriented programming languages allow data hiding using private fields. They use these to hide the internals of classes. In JavaScript there is no built-in support to hide/encapsulate the inner workings, but we can achieve encapsulation using anonymous functions.
Anonymous functions, particularly when used as Immediately Invoked Function Expressions (IIFEs), can create private scopes that prevent global namespace pollution and provide encapsulation.
The Problem: Global Namespace Pollution
When we declare variables and functions in the global scope, they become accessible everywhere and can cause naming conflicts:
const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) {
return (x + y) * HIDDEN_CONST;
}
console.log(fnWeWantToHide(1, 2));
console.log("Global pollution - HIDDEN_CONST is accessible:", HIDDEN_CONST);
300 Global pollution - HIDDEN_CONST is accessible: 100
Solution: Using IIFE for Encapsulation
We can wrap our code in an IIFE (Immediately Invoked Function Expression) to create a private scope:
(() => {
const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) {
return (x + y) * HIDDEN_CONST;
}
console.log("Inside IIFE:", fnWeWantToHide(1, 2));
})();
// Try to access the variables outside - they're not available
try {
console.log(HIDDEN_CONST);
} catch(error) {
console.log("HIDDEN_CONST is not accessible outside:", error.message);
}
Inside IIFE: 300 HIDDEN_CONST is not accessible outside: HIDDEN_CONST is not defined
Creating a Module Pattern
We can return selected functions or values to create a module-like structure:
const calculator = (() => {
const MULTIPLIER = 10;
const SECRET_KEY = "abc123";
function add(x, y) {
return (x + y) * MULTIPLIER;
}
function subtract(x, y) {
return (x - y) * MULTIPLIER;
}
// Return only what we want to expose
return {
add: add,
subtract: subtract
};
})();
console.log("Public add method:", calculator.add(5, 3));
console.log("Public subtract method:", calculator.subtract(5, 3));
// Private variables remain hidden
console.log("MULTIPLIER accessible?", typeof calculator.MULTIPLIER === 'undefined');
Public add method: 80 Public subtract method: 20 MULTIPLIER accessible? true
Comparison: With and Without Encapsulation
| Aspect | Without IIFE | With IIFE |
|---|---|---|
| Global Namespace | Polluted | Clean |
| Variable Privacy | All public | Private by default |
| Naming Conflicts | Possible | Prevented |
| Code Organization | Scattered | Modular |
Conclusion
Anonymous functions, especially IIFEs, provide effective encapsulation in JavaScript by creating private scopes. This prevents global namespace pollution and allows you to expose only the necessary parts of your code while keeping implementation details hidden.
