DEV Community

Discussion on: Closures in JavaScript

Collapse
 
wulymammoth profile image
David • Edited

Awesome post, Parwinder!

One clarification that I think is worth mentioning. My understanding is that the variable declared and initialized is not GC'd because there's a child function. I think it's actually simpler than that, right? It isn't GC'd so long as ANYTHING maintains a reference to it, whether it's a function, another variable, some object's state, etc

let bar = null;

(function outer() {
  const foo = "foo";
  bar = foo;
})(); // function has returned

console.log(bar); // still has access to foo
foo

Absolutely love the last example! I feel like people don't really know this and this is ideally how encapsulation is done. However, it may be worth mentioning that it's usefulness or utility comes from being able to enforce an interface -- forcing the consumer of the API to use the methods defined on the class instead of accessing properties/fields that aren't supposed to be accessible just because they can...

Collapse
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

David, great feedback ❤️

The more I write, the better writer I am becoming (or at least I think I am).

Then I see feedback like yours, and I am surprised that I could have presented things in a lot better way. I will update the post to reflect your feedback!

Collapse
 
wulymammoth profile image
David • Edited

You're doing great. I always miss a lot of things and love learning about what I've forgotten or don't yet know (there's a lot) :D

When I used to work in JavaScript and interview folks, I typically asked this question that is also solved with the use of a closure:

// what does the following return?
// unfortunately, after a second passes, we get a trail of sixes,
// because the function looks at `i` at invocation time
for (var i = 0; i <= 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

// we can "fix" this by employing an immediately-invoked function expression
// with closure maintaining the state of i at the time of construction
// the following will now print 0, 1, 2, 3, 4, 5
for (var i = 0; i <= 5; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i);
    }, 1000);
  })(i); 
}
Thread Thread
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Haha, I am glad that you have mentioned this example. This is a go-to question for me too.