DEV Community

Discussion on: Closure Explained!

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