Simplifying the magic of JavaScript closures with example
Alamin Shaikh
Developer/Maker. Building software for everyone. Recently launched ???? devcoa.ch
Closure is an advanced JavaScript concept that many developers find hard to understand. This concept feels confusing because it challenges our general understanding that an execution context and all the variables within it are removed once the execution is complete.
While this is generally true, it doesn't apply to closure. In JavaScript, closure is created for every function, allowing a function to retain access to all the variables it uses from its parent contexts, though the parent contexts have returned and finished their execution.
Let's understand this definition with an example:
function counter() {
let count = 0;
return function increment() {
count++;
console.log(count);
};
}
const increment = counter();
increment(); // 1
In the above code, we have a function called counter that contains a count variable and returns another function called increment. Within the increment function, we increment the count variable and log it to the console.
Are you enjoying the content? Read the rest of the article here.