Hi there,
In this post, Let's learn Closures.
Closures are essential in JavaScript because they allow a function to access variables from its parent scope, even after that parent function has closed. This is crucial for functions that need to remember data over time, like in callback functions or maintaining state. One point to remember here is the unused variables of parent scope are garbage collected.
Definition:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time.
Basically closures have access to:
Bonus Point
Lexical Scope : Inner functions have access to variables in outer scope.
Let's understand with example.
Example
Q> Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:
increment() increases the current value by 1 and then returns it.
decrement() reduces the current value by 1 and then returns it.
reset() sets the current value to init and then returns it.
See the commented code below for init = 5 case example.
Solution
var createCounter = function(init) { const INITIAL_VALUE = init; return { increment: () => ++init, decrement: () => --init, reset: () => init=INITIAL_VALUE, } }; /** * const counter = createCounter(5) * counter.increment(); // 6 * counter.reset(); // 5 * counter.decrement(); // 4 */
Explanation:
If you have any doubts or suggestions feel free to add in comments.
This question was taken from leetcode. Link
Lastly keep in mind that globally declared variables will be accessible to every closure in a script.
I hope now you have a good understanding of closures. Thank you for reading
The above is the detailed content of Closures in JavaScript. For more information, please follow other related articles on the PHP Chinese website!