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

Vladimir Plokhotniuk
Vladimir Plokhotniuk
5,464 Points

How "let" here working?

When we using 'let' instead of 'var', 'let' stores in one variable like 3 different values? because when i am look in debugger using 'let' , the variable 'buttonName ' all cycles undefined. But when 'var' - changing into first, second, third... ...or the loop is executed indefinitely?

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

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

There is a scope difference between let and var that might have an influence on what you are trying to do.

Maybe this link can help you out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Scoping_rules_2

1 Answer

20,469 Points

A var in a for loop is a global variable, because var can only have two kinds of scope: global scope, and function level scope (a scope limited to a certain function). A for loop is not a function, so the var has global scope in a for loop.

But let can have three kinds of scope: global, function level, and block level. Block level scope is scope limited to any block of code (anything surrounded by {}). A for loop is a block, so a let variable has local scope in the for loop.