Using let with for Loops2:25 with Andrew Chalkley
Using the var keyword in for loops can cause unexpected behavior. In this video we'll see how let solves those issues.
The let keyword is especially useful in for loops. 0:00 Using var to define the counter in a for 0:04 loop can lead to some really confusing and unexpected outcomes. 0:07 Let me show you one common example. 0:12 Open buttons.html and look at this example. 0:15 The program is designed to select all buttons on the page. 0:20 Then the program adds the behavior for when someone clicks on the button, 0:24 it produces an alert that says Button, then the Button number, Pressed. 0:31 The first button should say, Button 0 pressed. 0:38 The second button should say, Button 1 pressed, and so on. 0:41 Let's preview the code and see it in action. 0:47 When we press any button, it keeps saying Button 10 Pressed, why is that? 0:52 When you click the button, the alert displays the last value of i. 1:01 In other words, each time the loop runs, i is incremented by 1. 1:07 When the loop is complete, the value of i is 10. 1:13 Clicking any button displays the current value of i, this is not what we want. 1:19 We want each button number to appear. 1:28 The problem is related to scope. 1:31 The variable i lives in what's called the global scope, like this. 1:34 All the buttons share the same value of i. 1:44 What we need is to give each of the buttons its own local copy of i. 1:48 Fortunately, let allows us to do that. 1:54 This means that the let variable declaration of i is localized to each 2:01 cycle of the for loop. 2:06 In other words, the i variable is distinct for each cycle through the loop. 2:08 Let's preview that now. 2:13 When we click on any button, 2:17 we see that the correct number of the button gets alerted, fantastic. 2:19
You need to sign up for Treehouse in order to download course files.Sign up