Closures Javascript
Closures JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
-
What is a closure in javascript?
- A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the Lexical environment).
- In other words, a closure gives you access to an outer function's scope from an inner function even after the outer function has completed execution (returned).
- In JavaScript, closures are created every time a function is created, at function creation time.
-
Why closures?
- Data Encapsulation: Encapsulation OOPs
- Closures allow you to create private variables & methods. This helps in organizing code and preventing accidental modification of variables from outside the intended scope.
function createCounter() { let count = 0; return function() { return ++count; } } const counter = createCounter(); console.log(counter()); // 1 let count = 0; console.log(counter()); // 2 count = 0; console.log(counter()); // 3- The
countvariable is private & can only be accessed through the returned function.
- Maintaining State:
- Closures allow functions to "remember" their lexical environment, even after the outer function has finished executing. This is particularly useful for:
- Event Handlers: You can attach data to event handlers that are specific to the element the event is trigeered on.
- Callbacks: You can pass data to callback functions that will be used later.
- Iterators: You can create iterators that maintain their state across multiple calls.
- Closures allow functions to "remember" their lexical environment, even after the outer function has finished executing. This is particularly useful for:
- Functional Programming:
- Closures are a fundamental building block for Functional Programming Paradigms.
- They allow you to create higher-order functions that take functions as arguments & return functions.
- Module Pattern JavaScript
- Data Encapsulation: Encapsulation OOPs
-
Example 1:
// global scope function subscribe() { // inner scope 2 var name = "Chaitanya"; function displayName() { // inner scope console.log(name); // Chaitanya, [[Closures Javascript]] } displayName(); } subscribe(); // Chaitanya -
Example 2
function makeFunc() { var name = "Mozilla"; function displayName() { console.log(name); } return displayName; } var myFunc = makeFunc(); myFunc(); // Mozilla -
Example 3
function makeFunc() { var name = "Mozilla"; function displayName(num) { console.log(name, num); // Mozilla 5 } return displayName; } makeFunc()(5); // Mozilla 5
Closure Scope Chain (Currying)
var e = 10;
function sum(a) { // a = 1
return function (b) { // b = 2
return function (c) { // c = 3
return function (d) { // d = 4
return a + b + c + d + e;
};
};
};
}
console.log(sum(1)(2)(3)(4)); // 20