Mastering JavaScript Closures: Understanding and Using this Powerful Feature

Becoming an expert in JavaScript closures: A step-by-step guide

Manish Salunke
7 min readJan 22, 2023
JavaScript Closure
Photo by Cristina Gottardi on Unsplash

You can use JavaScript Closures to create private variables and methods, preserve object state across multiple function calls, and expose public APIs while keeping implementation details private. , is a powerful feature of the language. Understanding how closures work and how to use them effectively is an important skill for any JavaScript developer. In this blog, we dive deep into the world of closures, finding out how they work, why they are useful, and how to use them to write more conservative and efficient code.

First, let’s look at the basic structure of a JavaScript Closure and how closures are created. Then move on to more advanced topics such as creating private variables and methods, persisting state, and creating public APIs. Along the way, we provide examples and commentary to help you better understand this powerful feature.

Whether you’re a beginner or an experienced JavaScript developer, this blog provides the knowledge and skills you need to master closures and take your programming to the next level. Now let’s test the power of JavaScript closures.

Who I am?

My name is Manish Salunke, I am having 12 years of experience As a JavaScript Developer, and I have a deep understanding of the language and its ecosystem. Familiarity with various JavaScript design patterns and best practices, and ability to write clean, maintainable, and efficient code. Also, familiar with various JavaScript frameworks and libraries so I can react quickly to new technologies. I also have experience working with both front-end and back-end JavaScript, as well as integrating with other languages and technologies. Also has experience testing and debugging JavaScript code, so he can effectively troubleshoot and troubleshoot issues.

Let's get started on JavaScript Closure.

What is JavaScript Closure?

A JavaScript Closure function that has access to variables in its parent scope, even after the parent function has returned. Closures are created when a nested function references variables from its containing (outer) function.

JavaScript Closure example:

function outerFunction(x) {
let y = x + 89;

function innerFunction() {
console.log(y);
}

return innerFunction;
}

let closure = outerFunction(1);
closure(); // logs 90

In this JavaScript Closure example, innerFunction can access outerFunction’s variable y even after outerFunction returns.

JavaScript Closures can be used for things like creating private variables and methods, maintaining object state across multiple function calls, and exposing public APIs while keeping implementation details private.

When to use JavaScript Closures?

Examples of common uses of JavaScript Closures include creating private variables and methods. Declaring a variable within a function and returning a closure that can access that variable effectively creates a personal variable that can only be accessed through the closure.

This is useful for preserving object state and preventing external code from modifying the object’s internal state.

Another use case for JavaScript Closures is to maintain the state of an object across multiple function calls.

For example, consider JavaScript closure code like this:

function createCounter() {
let count = 0;
return function() {
count++;
return count;
}
}

let counter = createCounter();
console.log(counter()); // logs 1
console.log(counter()); // logs 2

Here, the createCounter function returns a closure that, when invoked, increments and returns a count variable.

The closure has access to the count variable even after the createCounter function has returned, so the count is preserved across multiple function calls.

JavaScript Closures can also be used to expose public APIs while keeping implementation details private.

For example, consider the following code:

function createPerson(name) {
let age = 0;
return {
getName() {
return name;
},
setAge(newAge) {
age = newAge;
},
getAge() {
return age;
}
}
}

let person = createPerson("Manish");
console.log(person.getName()); // logs "Manish"
person.setAge(35);
console.log(person.getAge()); // logs 35

Here, the createPerson function returns an object with three methods: getName, setAge, and getAge.

The name variable is passed as an argument to the function, and the age variable is declared within the function, but both can be accessed through the returned object’s methods.

This allows you to keep the implementation details private while still providing a public API for interacting with the object.

How JavaScript Closure Works?

The function provides the variables that were in scope at the time the function was defined, and the scope the function captures.

When a function is called, it is the execution context of the function itself.

So you can refer to the parent function’s variables after the parent function has returned.

For example, consider the following code:

function outerFunction(x) {
let y = x + 88;

function innerFunction() {
console.log(y);
}

return innerFunction;
}

let closure = outerFunction(5);
closure(); // logs 93

In this example, innerFunction can access the variable y from outerFunction even after outerFunction returns.

Because innerFunction is a closure that can access the parent function’s scope.

Also, defining a variable inside a closure and returning the closure means that the variable’s value and state can be retained after the function that created the closure returns.

Closures also feature that the closure scope is accessible not only to the inner function but also to any function defined within the closure scope.

How to clear JavaScript Closure?

In JavaScript, there is no direct way to say “clear”. But there are a few ways you can effectively “clear” a JavaScript closure by breaking the references that are keeping it alive.

One way is to set the closure variable to null or undefined. This will break references to the closure and allow the garbage collector to reclaim the memory used by the closure functions and variables. This method is only valid if there is no reference to the closure.

Another way to remove all event listeners that use the javascript closure, Also remove all references to the closure. This breaks the reference and allows the garbage collector to reclaim memory.

Also, if you use the delete operator to remove a property from the object containing the closure, the reference is dereferenced and the closure becomes eligible for garbage collection.

Finally, using WeakMap objects to store closures allows the garbage collector to clean them up when there are no more references to them.

Also note that in some cases you don’t need to explicitly clean up closures, as JavaScript’s garbage collector cleans up obsolete closures automatically.

If you are dealing with a large number of closures or face memory issues, you should consider one of the above methods to clear closures and free up memory.

Keep in mind that, in most cases, it’s not necessary to clear closures, the garbage collector will take care of it. But in some specific cases, it’s important to clear the closure manually to avoid memory leaks and other issues.

Why do we use JavaScript Closures?

One of the main advantages of JavaScript Closures is the ability to create private variables and methods. It preserves the object’s state and prevents external code from changing the object’s internal state.

Another benefit of JavaScript Closures is that it allows you to persist an object’s state across multiple function calls. And is useful for creating functions that need to maintain state, or factory functions that return objects that have methods that need to maintain state.

JavaScript Closures can also be used to expose public APIs while keeping implementation details private.

JavaScript Closures can also be used to emulate the behavior of object-oriented languages. JavaScript Closures allow you to define methods on objects and make their state private.

Here are a few more JavaScript Closure examples:

JavaScript Closure that maintains a private variable:

function createCounter() {
let count = 89;
return {
increment() {
count++;
},
getCount() {
return count;
}
}
}

let counter = createCounter();
counter.increment();
console.log(counter.getCount()); // logs 90

In above JavaScript Closure example, the createCounter function returns an object with two methods: increment and getCount. The count variable is declared within the createCounter function, but can be accessed or changed in methods of the returned object. This is possible because the method is a closure and can access variables in its parent scope.

JavaScript Closure that preserves the state across multiple function calls:

function createAdder(x) {
return function(y) {
return x + y;
}
}

let add5 = createAdder(50);
console.log(add5(20)); // logs 70
console.log(add5(40)); // logs 90

In the above example, the createAdder the function returns a closure that, when invoked, adds its argument to the x variable passed to the createAdder function. The JavaScript Closure has access to the x variable even after the createAdder the function has returned, so the value of x is preserved across multiple function calls.

JavaScript Closure that exposes a public API while keeping the implementation details private:

function createPerson(name) {
let age = 0;
return {
getName() {
return name;
},
setAge(newAge) {
age = newAge;
},
getAge() {
return age;
}
}
}

let person = createPerson("Manish");
console.log(person.getName()); // logs "Manish"
person.setAge(35);
console.log(person.getAge()); // logs 35

In the above example, the createPerson the function returns an object with three methods: getName, setAge, and getAge. The name the variable is passed as an argument to the function, and the age variable is declared within the function, but both can be accessed through the returned object's methods. This JavaScript Closure allows you to keep the implementation details private while still providing a public API for interacting with the object.

Conclusion

JavaScript closure is a powerful feature that helps you write more conservative and efficient code. Closures allow you to create private variables and methods, maintain object state across multiple function calls, and expose public APIs while keeping implementation details private. . Understanding how closures work and how to use them effectively is an important skill for any JavaScript developer.

I hope this blog gives you a deeper understanding of JavaScript Closure and how to use them in your projects.

If this blog was helpful, I will continue to write informative and helpful blogs. I want to share the latest trends and best practices in the world of JavaScript development.

If you have any questions or comments, feel free to write them in the comments section below. Willing to help if you have any problems and answer any questions.

thank you for reading. Happy coding!

--

--