Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Defining Variables with let and const!
Preview
Video Player
00:00
00:00
00:00
- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
Using constants are a best practice when assigning variables but what happens when you do actually want to reassign a value? That's where let comes in.
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 used when you
want to re-assign a variable.
0:00
In that respect, It just works like var.
0:04
Let's take a look at a simple example.
0:07
Open up let.html, and you can
see we've got the score = 0 and
0:09
age = 33, and a boolean is hungry = false.
0:16
Open up the preview and
navigate to let.html.
0:22
Open up the console, and
let's try and modify the score.
0:28
The score can change through a game.
0:36
The score increments by one each time
the player completes a challenge.
0:38
Again, let just works like var.
0:43
You can reassign values to a variable
that is declared with the let keyword.
0:47
You can update the age to be 34.
0:53
And is hungry.
0:57
To be true.
1:05
Let's look at a more complex example where
you should use let rather than a const.
1:07
Open up person.html, and
here we have a function called
1:14
personDescription that
creates a description string.
1:18
That gets logged out at the end here.
1:24
If the person object has a role,
1:27
it will add additional information at the
end of the description and is logged out.
1:33
Let's see this in action.
1:40
Go to the preview.
1:42
Click on person.html,
1:43
open up the developer console and
we should see Andrew is a teacher.
1:46
If we change the var keyword in
the person description function to const.
1:52
And run it again we get an error, because
we're trying to re-assign the description
1:59
in the if block,
We could change it to var,
2:06
or alternatively we could
use the new let keyword.
2:12
Let works like var,
allowing you to re-assign variables, but
2:18
unlike var, it has block level scoping.
2:23
We'll explore when we'd see the advantages
of using let over var in the next video.
2:26
Now that we've changed the const to let,
let's see how it works in our browser.
2:32
Looking in the console, we see Andrew is
a teacher printed out like we expect.
2:38
In the next video,
2:42
we'll look at how let solved some problems
where the var keyword falls short.
2:43
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