DEV Community

Cover image for Closure Explained!
Bhavesh Kasturi
Bhavesh Kasturi

Posted on

Closure Explained!

Let's Define Closure

A closure is a function that makes use of variable defined in outer functions that have previously returned. What does this mean, Let's quickly look at an example.

function outer(a){
    return function inner(b){
        return a + b;
    }
}
outer(5)(5); // 10
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, the function inner uses the variable "a" declared in a function named "outer," and when the function inner is called, the function outer returns the function called "inner," and this is called as a closure!

A few things to note:

  • We have to 'return' the inner function for the above example to work.
  • We can call the inner function right away by using an extra ().
  • We don't have to name the inner function (we just called it "inner" for learning purposes)

How Closures Work

Only variables used in the inner function are stored!
Closures don't remember everything from an outer function - just the variables they require!

Why do I need to know this?

Private Variables

Variables that cannot be updated externally are supported in other languages. These are referred to as private variables, although they are not included in JavaScript. No need to be concerned - closures can assist!

function counter(){
    let count = 0;
    return function(){
        count++;
        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode
const counter1 = counter();
counter1(); // 1
counter1(); // 2

const counter2 = counter();
counter2(); // 1
counter2(); // 2

counter1(); // 3 this is unaffected by counter2.

console.log(count); 
// Uncaught ReferenceError: count is not defined - because it is private!
Enter fullscreen mode Exit fullscreen mode

TL;DR

  • Closure is when an inner function makes use of variables declared in an outer function that has previously returned.
  • JavaScript will only remember values that are being used inside of the inner function, not all variables defined in the outer function.
  • Closures allow us to define private variables and write cleaner code that separates our logic from our application.

Thank you for making it till the end!

Top comments (5)

Collapse
 
mayankav profile image
mayankav • Edited

@duhbhavesh Hello Bhavesh, thanks for writing this. Honestly, I would like to correct you on 3 of the 4 points you made in the conclusion.

Closure exists when an inner function makes use of variables declared in an outer function that has previously returned.

That's incorrect Bhavesh. Every function in JavaScript closes over its surrounding as soon as the function itself comes into existence. Read this.

Closure does not exist if you do not return an inner function and if that inner function does not make use of variables returned by an outer function.

This can be misleading. I won't blame you for this. As a matter of fact it doesn't matter whether the function is returned or not, called or not, the closure does exist.

JavaScript will only remember values that are being used inside of the inner function, not all variables defined in the outer function.

Again, that's not true. Check this image for reference. For handson try experimenting on this visualizer.

The Symbol Fairy

Online Visualizer

I put up a post on how closures really work under one level of abstraction. I'd recommend you try giving it a read.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

That visualiser may say that noUse is in scope, but Chrome doesn't have things not used in the function as part of the implemented scope during the execution of the inner function.

function a() {
    let x = 1
    let y = 2
    return function b() {
        debugger
        return y
    }
}
a()()
Enter fullscreen mode Exit fullscreen mode

Run that in a Chrome debug console and only the y variable is part of the scope.

image

Collapse
 
mayankav profile image
mayankav • Edited

@miketalbot Hey Mike! Good point. I was expecting this :) I clarify something similar in my post here. Though v8 does not show it in the console, it is only an engine optimization. I'd repeat myself again only to say that closures are formed as soon as a function is created and that all the references of the surrounding scope are indeed a part of the closure. To be honest this visualizer does it better than v8 when it comes to visualizing closures and scopes. I'd have to agree that JS engines do optimize stuff internally, the reason being most of the time we really do not care about closures unless an internally returned function executes beyond its lexical scope.

Collapse
 
duhbhavesh profile image
Bhavesh Kasturi

Hey @mayankav Thanks for opening up the discussion, I may have misunderstood closures. Thanks for letting me know.

Collapse
 
mayankav profile image
mayankav

@duhbhavesh pleasure