1 00:00:00,390 --> 00:00:04,340 The let keyword is especially useful in for loops. 2 00:00:04,340 --> 00:00:07,460 Using var to define the counter in a for 3 00:00:07,460 --> 00:00:12,650 loop can lead to some really confusing and unexpected outcomes. 4 00:00:12,650 --> 00:00:15,150 Let me show you one common example. 5 00:00:15,150 --> 00:00:20,400 Open buttons.html and look at this example. 6 00:00:20,400 --> 00:00:24,810 The program is designed to select all buttons on the page. 7 00:00:24,810 --> 00:00:29,180 Then the program adds the behavior for when someone clicks on the button, 8 00:00:31,370 --> 00:00:37,140 it produces an alert that says Button, then the Button number, Pressed. 9 00:00:38,270 --> 00:00:41,990 The first button should say, Button 0 pressed. 10 00:00:41,990 --> 00:00:47,090 The second button should say, Button 1 pressed, and so on. 11 00:00:47,090 --> 00:00:50,595 Let's preview the code and see it in action. 12 00:00:52,580 --> 00:00:58,429 When we press any button, it keeps saying Button 10 Pressed, why is that? 13 00:01:01,116 --> 00:01:07,240 When you click the button, the alert displays the last value of i. 14 00:01:07,240 --> 00:01:13,120 In other words, each time the loop runs, i is incremented by 1. 15 00:01:13,120 --> 00:01:19,860 When the loop is complete, the value of i is 10. 16 00:01:19,860 --> 00:01:28,630 Clicking any button displays the current value of i, this is not what we want. 17 00:01:28,630 --> 00:01:31,490 We want each button number to appear. 18 00:01:31,490 --> 00:01:34,440 The problem is related to scope. 19 00:01:34,440 --> 00:01:41,216 The variable i lives in what's called the global scope, like this. 20 00:01:44,254 --> 00:01:48,660 All the buttons share the same value of i. 21 00:01:48,660 --> 00:01:54,050 What we need is to give each of the buttons its own local copy of i. 22 00:01:54,050 --> 00:01:58,480 Fortunately, let allows us to do that. 23 00:02:01,238 --> 00:02:06,236 This means that the let variable declaration of i is localized to each 24 00:02:06,236 --> 00:02:08,210 cycle of the for loop. 25 00:02:08,210 --> 00:02:13,970 In other words, the i variable is distinct for each cycle through the loop. 26 00:02:13,970 --> 00:02:15,347 Let's preview that now. 27 00:02:17,170 --> 00:02:19,030 When we click on any button, 28 00:02:19,030 --> 00:02:23,690 we see that the correct number of the button gets alerted, fantastic.