Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kristian Woods
23,414 PointsDo I understand the concept of closures?
So, just so I have a clear understanding of what a closure is, I'm going to attempt to explain it
function retirement(retirementAge) {
var a = ' years left until retirement';
return function(yearOfBirth) {
var age = 2018 - yearOfBirth;
console.log((retirementAge - age) + a);
}
}
var retirementUS = retirement(66);
retirementUS(1989);
When creating the retirementUS variable, the outer retirement function runs and the parameter (66) is passed. That function is then popped off the execution stack and the inner function is now stored in the retirementUS variable. BUT the variable 'a' is stored in memory - thats why the inner function has access to the variable, even AFTER the outer function has returned. You are then able to pass the yearOfBirth parameter to the retirementUS function. The benefit of this, is that the variables are kept private and can't be changed by other code.
Is this right?
2 Answers
Clayton Perszyk
Treehouse Moderator 49,057 PointsI would say that sounds like a good expalanation. The idea of data hiding is defintely one of the key uses of closures.
Kristian Woods
23,414 PointsThanks, Clayton. Other than naming conflicts and keeping variables private. What are the main real world reasons for using closures? Also, now that the keyword “let” and “const” have block level scoping. Are closures still needed as much as they have been in the past?