JavaScript Using let with for Loops

I didnt get any part of this tutorial. I am completely lost. Can anyone plz break down the code..!

I didnt get any part of this tutorial. I am completely lost. Can anyone plz break down the code..! Specially where the instructor tells the difference between 'var' and 'let'. How does the 'i' remain equal to 10 by using var.?

3 Answers

Samuel Ferree
Samuel Ferree
31,566 Points

The difference between 'var' and 'let' is what's known as block level scoping, in laymans terms, variables defined with 'let' only exist in between the pair of curly braces that starts right before the variable is defined. See below

var x = 2; //This variable exists from here on out
  var y = 3; //This variable also exists for the rest of the execution
  let z = 4; //This variable only exists inside the outer curly braces
    //all variables exists here, even z, since this scope is 'inside' the parent scope
// x and y can be used here, 
// but we are no longer in the scope in which z was declared with 'let'

Hope this helps.

Jason Anders
Jason Anders
Treehouse Moderator 127,780 Points

Hi Sal,

Although it is marked as "Beginner", this is a Workshop and not a course, so it assumes that you have at least a working knowledge of the programming language in which the feature of the workshop is based in.

Looking at your question, I'm assuming that you are new to coding and to JavaScript. The in-depth answer to your question does go a bit beyond the scope of a Community Forum post....
Instead, I think you will find the Digital Literacy Track very interesting and informative. This track is specifically designed to give you an introductory working knowledge of computers and coding, which will be greatly beneficial as you progress with your coding journey.

Give it a look and Keep Coding! :) :dizzy:

Thankyou Jason,

I do have a working knowledge of the programming language. I have been learning from other sites and online tutorials but I just heard about treehouse and signed in to its free trial. So i came across this tutorial and did not get anything the instructor is saying.


Akash Sharma
Akash Sharma
Full Stack JavaScript Techdegree Student 10,729 Points
for(var i = 0; i < buttons.length; i++) {
          const button = buttons[i];
          button.addEventListener("click", function() {
              alert("Button " + i + " Pressed");

Remember that i++ in the for loop will executed right before another loop iterates, but since 10 < 10 is false loop will terminate and now every button has an event listener that we programmed for an alert. The problem is that since var i is global scope and now any other variable that used it will have i = 10.

Prabal Dutta
Prabal Dutta
85 Points

How is buttons.length = 10?