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

I thought I get "let" until I saw this video. How does "let" solve this problem, exactly?

var buttons = document.getElementsByTagName('button');

for(var i = 0; i < buttons.length; i += 1) {
    var button = buttons[i];
    let buttonName = button.innerHTML;
    button.addEventListener('click', function(){
    console.log(buttonName);
  });
}

If the let keyword has a block scope, I think that, after the loop is finished, shouldn't exist a reference to the buttonName variable anymore, making the click event log "undefined".

Isn't that right? The variable declared with "let" only exists for that block, so I think that, after the for loop is done, the buttonName variable wouldn't be acessable anymore.

Can someone please explain how does this work in detail?

Thank you!

Brandon Khan
Brandon Khan
21,619 Points

let allows for block scope as you are saying, each time your loop runs let will make a new variable not override the last one like with var. In your example buttonName is only accessible in the for loop. Also note i is accessible in function scope or global depending on the rest of your code. This may be an older video I'm not sure if closer in functions are needed after js got let and const.