NESTED
CLOSURES
So, what exactly are nested
closures? 🤔
Althogh, closures are themsef nested
but here is a catch, Imagine a
function within another function,
where the inner function has access
to the variables and parameters of
the outer function. This
encapsulation allows for some truly
elegant and powerful solutions to
complex programming challenges.
Example - 1
function outerFunction(outerParam) {
return function innerFunction(innerParam) {
return outerParam + innerParam;
};
}
const nestedClosure = outerFunction(10);
console.log(nestedClosure(5)); // Output: 15
In this example, innerFunction is nested
within outerFunction, and it has access to
the outerParam variable declared in
outerFunction. This enables us to create
reusable, modular code with clear separation
of concerns.
Example - 2
function createPerson(name) {
let age = 42;
return {
getName: function() {
return name;
}
celebrateBirthday: function() {
return age++;
}
}
}
let person = createPerson(‘MS Dhoni’);
console.log(person.getName()); // MS Dhoni
person.celebrateBirthday() // updated age
console.log(person.celebrateBirthday()); // 43
🌟 Key Benefits 🌟
1. Encapsulation: Nested closures enable
encapsulation of data within a function
scope, preventing pollution of the global
scope and enhancing code organization and
readability.
2. Maintaining State: The inner function
retains access to the variables of the outer
function even after the outer function has
completed execution, allowing for the
preservation of state across multiple
function calls.
3. Flexible and Modular Code: Nested closures
facilitate the creation of modular and
reusable code by allowing functions to be
defined within functions, promoting code
reusability and maintainability.
Repost & help others
Like
Found
Helpful? Comment
Follow for more
Share