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

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() {
        console.log(buttonName);
    });
}

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

odzer
odzer
20,483 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.