Sitemap
Kruthi Venkatesh

Kruthi Venkatesh

My mantra Learn, Unlearn, and Relearn!

Member-only story

JavaScript Series: Closures

2 min readDec 1, 2023

--

A closure is a function that “closes over” its lexical scope, meaning it retains access to variables and parameters from the surrounding scope even after that scope has finished executing.

Closures are often used to encapsulate data and behavior, creating more modular and maintainable code.

function createCounter() {
let count = 0; // This variable is encapsulated within the closure.

function increment() {
count++;
console.log(`Count: ${count}`);
}

function reset() {
count = 0;
console.log("Count reset to 0.");
}

return {
increment,
reset
};
}

const counter = createCounter();

counter.increment(); // Increments count: 1
counter.increment(); // Increments count: 2
counter.reset(); // Resets count to 0

In this example,

The createCounter function encapsulates a count variable and two functions (increment and reset) within a closure.

The returned object provides controlled access to these encapsulated elements.

Users of the counter object can increment the count and reset it, but they can't directly access or modify the count variable from outside the closure.

Benefits of Closures

Data Encapsulation:

Private Data: Variables and methods encapsulated within closures are effectively private because they are not accessible from outside the closure, which…

--

--

Kruthi Venkatesh
Kruthi Venkatesh

Written by Kruthi Venkatesh

My mantra Learn, Unlearn, and Relearn!