Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,618 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.