Javascript closure

xharlessnowxharlessnow
1 min read

A closure in programming refers to the ability of a function to "remember" the variables in its lexical scope (the environment in which it was created). It's like the function "closes over" these variables, retaining access to them even after the outer function has finished executing.

In the example of the counter function:

var createCounter = function(n) {
    return function() {
        return n++;
    };
};

const counter = createCounter(10);
console.log(counter()); // Output: 10
console.log(counter()); // Output: 11
console.log(counter()); // Output: 12

Here, the createCounter function returns an inner function that has access to the n variable. When you call createCounter(10), it creates a closure around the variable n with an initial value of 10. The inner function is assigned to the variable counter.

Now, when you call counter(), it returns the current value of n (10 in the first call) and increments n for the next call. The closure allows the inner function to remember the state of n between calls.

Think of it like the inner function "closes over" the n variable, enclosing it within its scope and preserving its state. This is a powerful concept in JavaScript and is often used for creating functions with persistent state.

0
Subscribe to my newsletter

Read articles from xharlessnow directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

xharlessnow
xharlessnow

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'. "While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."