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 Uses for Closures

brandonlind2
brandonlind2
7,823 Points

I'm a bit confused on this video? There is only one variable with buttonName

I'm a bit confused as to were the conflict is with the buttonName varibles is there a conflict with the name because there is another varible named buttonName is out of view in another file or something?

3 Answers

Steven Parker
Steven Parker
231,248 Points

:point_right: There is only one variable buttonName.

In fact, that's what causes the issue. Since there's only one, if it has global scope, then each button will return the name of the last button that got a handler.

But by using a closure (or by creating a new scope using "let"), each button returns its own name.

He didn't really explain what was happening in the loop taking the last value of the array, and this video was inadequate. This workshop should be redone with a more thorough explanation.

Laura Jackson
Laura Jackson
9,519 Points

It will continuously overwrite your button, so the final answer "Third " will always be the result. Adding in the closure and you can create a name for each, with no risk of being overwritten.

The loop continues until the end, without creating new name. So the name gets overwritten, as the loop will complete and then the result is whatever it is.

**Have a look at the process of looping and this will display exactly what happens in run time. This helped me, to visually see it, I hope it can help you.