Closures: Understanding Advanced JS Concepts

In JavaScript, closure is a combination of a function and the lexical environment in which that function was declared.

In simpler terms, a closure is a function that has access to variables and parameters in its outer (enclosing) function, even after the outer function has finished executing and returned. This allows the inner function to maintain access to the outer function's variables and state, even when it is called from outside the outer function.

Suppose we want to use a variable for counting something, and we want this counter to be available throughout the entire scope.

We could use a global variable and a counter() to increase the count:

// First Solution (Incorrect)
const counter = () => {
    let value = 0;
    value += 1;
    return value;
}

console.log(counter()); // 1
console.log(counter()); // 1
console.log(counter()); // 1

// every time the `value` is reinitialized and return after adding 1 to it

// Second Solution (Correct, Not Optimal)
let count = 0;

const counter () => {
    count += 1;
    return count;
}

counter();
counter();
...

// Since, count variable is in global scope and it can be altered by any other function or method.

To solve the above problem, we need closure. We need a function that has access to a local variable but is also private to it.

const counter = () => {
    let value = 0;
    console.log(`Initial value: ${value}`);
    return () => value += 1;
};

const getCounter = counter(); // Initial value: 0
console.log(getCounter()); // 1
console.log(getCounter()); // 2
console.log(getCounter()); // 3

In the given example, the variable value is declared within thecounter function and can only be accessed by the function returned by counter. This means that value acts as a private variable, as it cannot be accessed or modified directly from outside the returned function.

Furthermore, the returned function maintains a reference to the value variable through a closure, even after the counter function has finished executing. This means that each time the returned function is called, it can access and modify the same value variable, as it still exists within the closure.

This technique of using closures to create private variables and functions is a powerful feature of JavaScript, as it allows for better encapsulation and information hiding. By restricting access to certain variables and functions, developers can create more robust and maintainable code that is less prone to bugs and errors.

Did you find this article valuable?

Support Zeeshan Ashraf' Blogs by becoming a sponsor. Any amount is appreciated!