Closures 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 remem…


This content originally appeared on DEV Community and was authored by Yashraj

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
 */

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


This content originally appeared on DEV Community and was authored by Yashraj


Print Share Comment Cite Upload Translate Updates
APA

Yashraj | Sciencx (2024-09-11T19:27:50+00:00) Closures in JavaScript. Retrieved from https://www.scien.cx/2024/09/11/closures-in-javascript-2/

MLA
" » Closures in JavaScript." Yashraj | Sciencx - Wednesday September 11, 2024, https://www.scien.cx/2024/09/11/closures-in-javascript-2/
HARVARD
Yashraj | Sciencx Wednesday September 11, 2024 » Closures in JavaScript., viewed ,<https://www.scien.cx/2024/09/11/closures-in-javascript-2/>
VANCOUVER
Yashraj | Sciencx - » Closures in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/11/closures-in-javascript-2/
CHICAGO
" » Closures in JavaScript." Yashraj | Sciencx - Accessed . https://www.scien.cx/2024/09/11/closures-in-javascript-2/
IEEE
" » Closures in JavaScript." Yashraj | Sciencx [Online]. Available: https://www.scien.cx/2024/09/11/closures-in-javascript-2/. [Accessed: ]
rf:citation
» Closures in JavaScript | Yashraj | Sciencx | https://www.scien.cx/2024/09/11/closures-in-javascript-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.