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!

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

JavaScript Fixing Our Problem with Closures

Do I understand this?

If I understand it correctly, the someCount variable does not reset because when the outer function is called and set to a variable, that variable itself contains the state - the someCount variable. Then the returned inner function can be called repeatedly, modifying the state contained in the variable. Is that right?

1 Answer

Brady Snuggs
Brady Snuggs
9,602 Points

You understand it correctly.

I would add that the variable that's initialized with the outer-function serves as a memory address, like that of a class, to that new instance of the outer-function. Every new variable name, that has the outer-function called, is a new memory address that contains its own 'counter' variable - as well as every inner function that's modifying its respective counter variable.

So, another way of putting it would be, each memory address created with a new variable has its own 'counter' state that is being modified each time the inner-function is executed like you described.