DEV Community

Nishanthan K
Nishanthan K

Posted on

Mastering Closures in JavaScript: Understanding Scope, Encapsulation, and Performance

Closure

Definition

Closure is a feature that allows the functions to access all other variables and functions which are declared in same scope level (lexical scope).

  • Closure is a feature that allows the functions to access all other variables and functions which are declared in same scope level (lexical scope).
  • Closure will be created when a function is defined within another function (outer function and inner function). The inner function will create a closure that provides access to inner function to all variables and functions created in that outer function.
  • Closures allow the inner function to access variables declared in the outer function, even after the outer function has returned.
  • We have to handle the memory properly, closure can lead to both memory leak and better memory management.
  • Closures in JavaScript serve a similar purpose to private methods in Java by allowing you to create private variables and encapsulate functionality.

    Example

    function outerFunction() {
        let outerVariable = 'I am from outer scope';
    
        function innerFunction() {
            console.log(outerVariable); // Accessing outerVariable from the outer scope
        }
    
        return innerFunction; // Return the inner function
    }
    
    const closureFunction = outerFunction(); // Call outerFunction, which returns innerFunction
    closureFunction(); // Outputs: I am from outer scope
    
    • See in the above example we calling inner function only because it is only returned. Eventhough we have access to outerVariable.
    • Let’s see another best example
        function handleCount() {
        let count = 0;
    
        return {
            increment: () => {
                    count++;
                    return count;
            },
            decrement: () => {
                    count--;
                    return count;
            },
            getCount: () => {
                    return count;
            },
        };
    }
    
    const counter = handleCount();
    console.log(counter.increment()); // Outputs: 1
    console.log(counter.increment()); // Outputs: 2
    console.log(counter.getCount());  // Outputs: 2
    console.log(counter.decrement()); // Outputs: 1
    console.log(counter.getCount());  // Outputs: 1
    
    • Now for every time we called increment, decrement, getCount not handleCount will get initiated only the called function will get executed but also we have access to the variables outside of it scope. This is called as closure.

Key points to remember

  • Definition: A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
  • Scope Chain: Closures are created when a function is defined within another function. The inner function forms a closure that includes the outer function’s scope.
  • Access to Variables: Closures allow the inner function to access variables declared in the outer function, even after the outer function has returned.
  • Private Variables: Closures are often used to create private variables. This means that variables can be hidden from the global scope and only accessed through the closure.
  • Memory Management: Closures can lead to better memory efficiency, as they retain only the variables that are needed for execution.
  • Performance Considerations: While closures are powerful, they can also lead to memory leaks if not managed properly, especially in long-lived objects or event listeners.

Use cases

  • Encapsulation: To create private data or methods.
  • Function Factories: To create functions with preset parameters.
  • Callbacks: For asynchronous programming (like in event handlers or setTimeout).
  • CSS: rem and em. rem is derived from root element (html / body) but em is derived from its near parent.

Common interview questions

  • What is a closure, and how does it work?
  • Can you explain the difference between a closure and a regular function?
  • Provide an example of a closure in JavaScript.
  • What are the use cases of closures in JavaScript?
  • How can closures lead to memory leaks, and how can you prevent them?

Top comments (0)