DEV Community

Cover image for Closures : Important concept in JavaScript
Yashraj
Yashraj

Posted on • Updated on

Closures : Important concept in JavaScript

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:

  • Their own scope
  • The scope of the outer functions
  • The global scope

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
 */
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Capturing the init variable in its lexical scope.
  • Returning methods that can access and modify init even after createCounter finishes executing.
  • Creating a private, persistent state (init) that's accessible only through the returned methods.
  • Allowing creation of multiple independent counters, each with its own encapsulated state.

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

Top comments (0)