Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Using the var keyword in for loops can cause unexpected behavior. In this video we'll see how let solves those issues.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
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 zero pressed.
0:38
The second button should say,
button one pressed, and so on.
0:42
Lets preview the code and
see it in action.
0:47
When we press any button,
it keeps saying button ten pressed.
0:52
Why is that?
0:57
When you click the button,
the array displays the last value of i.
1:01
In other words each time the loop runs,
i is incremented by one.
1:07
When the loop is complete, the value of i
1:13
is ten clicking any button
displays the current value of i.
1:18
This is not what we want.
1:26
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.
1:34
Like this.
1:39
Only 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:14
When we click on any button,
2:17
we see that the correct number
of the button get selected.
2:19
Fantastic.
2:23
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up