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

JavaScript Fixing Our Problem with Closures

var birdCounter = makeCounter(); Isn't the birdCounter a variable? But why when we call it, it becomes: birdCounter()

I tried assigning method to a variable in other files, but the variable can't be appended the '()'

2 Answers

Steven Parker
Steven Parker
231,248 Points

Since calling makeCounter returns another function, then birdCounter contains a reference to that function. So even though birdCounter is a variable, since its contents refer to a function you can "call" it just like you would call a function.

And anytime you call a function you put parentheses after the name. If it used a parameter (this one does not), you would add an argument inside the parentheses.

Given var birdCounter = makeCounter();

Therefore, birdCounter() essentially runs makeCounter()()

The added caveat is that since birdCounter() is a variable that has access to the (inner) function, it can retain the private scope count variable within the inner-function of makeCounter()

But that leads to another question, how come when I run birdCounter,not to be confused with birdCounter(), the count doesn't reset to 0?

Steven Parker
Steven Parker
231,248 Points

Without the parentheses, birdCounter is just a reference to the function, it doesn't call it (cause it to run).