TechMentorAI

Closures

in JavaScript

Published

A closure in JavaScript is like a personal diary. Imagine you have a personal diary where you note down your secrets. Only you can access everything written in it, but anyone can read what's on the first page, where you might have put some general information. Same way in JavaScript, a closure is a function that has access to its own variables, its outer function's variables, and the global variables, just like the diary.

Imagine Closures in JavaScript

How does a closure work?

Normally, in JavaScript, when a function finishes executing, its local variables get deleted. But with closures, it's like the function carries around a backpack with it. Even after the function finishes up, the backpack (closure) sticks around in memory. This backpack is not accessible or visible to anyone else but it can be used the next time the function runs.

function outerFunction() {
    var secret = 'I have a secret';
    function innerFunction() {
        console.log(secret);
    }
    return innerFunction;
}

var getSecret = outerFunction();
getSecret(); // outputs: 'I have a secret'

Why use closures?

Closures are frequently used because they allow data to be kept alive indefinitely. It's as if the function locks its surrounding variables into a little box for later use. They can be used to emulate private methods or state, i.e., data hiding, in JavaScript. Another use case is when you use function factories, where a function returns another function that can have access to the parent function's scope.

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.07 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

Imagine you have a box. Let's call it 'daddyBox'. Inside the daddyBox, there is a smaller box called 'babyBox'. Now, the babyBox wants to use a toy that is in the daddyBox. A closure in JavaScript works like this. Even if the babyBox is moved to another room, it remembers and can still use the toy from the daddyBox.

Imagine Closures in JavaScript

Why do we use Closures?

Now, why would the babyBox want to use the toy from the daddyBox even in another room? Sometimes, we use closures in JavaScript to remember a value or access a variable from the daddyBox (which we call an outer function) even when we're in the babyBox (which we call an inner function). This way, we can use the same toy (or variable) in different rooms whenever we need to.

How do we use a Closure?

Here is a simple example of a closure. We have a daddyFunction and inside it there’s a babyFunction. The babyFunction remember and uses a toy named 'greeting' which is from daddyFunction. Even when babyFunction is called outside of daddyFunction, it still remembers greeting!

function daddyFunction() { 
    var greeting = 'Hi!'; 
    function babyFunction() { 
        alert(greeting); 
    } 
    return babyFunction;
} 

var sayHi = daddyFunction(); 

sayHi(); // alerts 'Hi!'

Understanding Closures Further

Closures might seem a bit tricky at first. But once you understand it, you realise it's pretty cool, almost like magic! Remember that the babyBox can keep using the toy from the daddyBox, even if it's in a different room. The same way, in JavaScript, the babyFunction can keep using the 'greeting' variable from the daddyFunction even if it's no longer inside the daddyFunction.

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.27 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

To understand how closures connect with JavaScript functions, it might be helpful to read about Function Scope in JavaScript

About author

Roman Y.
Senior Software Engineer at Nike

Why did I decide to launch this website? Drawing from my rich background in interviewing candidates for a variety of developer roles, I've observed a common pattern: many applicants share similar deficiencies in their knowledge during technical interviews. Motivated by this insight, I established this website with the aim of assisting developers in securing their ideal job. Through straightforward and concise articles, my goal is to not only deepen your understanding of programming language nuances but also to equip you with the insights needed to deliver the precise answers interviewers expect. Essentially, you'll be providing the correct response. I encourage you to spread the word about this site on social media platforms. Echoing the wisdom of an Armenian saying: "Do good and cast it into the water."

EXCLUSIVELY

Certain articles only distributed to subscribers through email