Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Carlos Chang Cheng
Courses Plus Student 12,030 PointsWhy do we use in the for loop the "let"?
const myList = document.getElementsByTagName('li');
for (let i = 0; i < myList.length; i+= 1) {
myList[i].style.color = 'purple';
}
Why you're using the let i=?
when typing just
(i=0; i < myList.length; i+= 0)
works fine.
Thanks!
2 Answers
Benjamin Larson
34,055 PointsPasted from MDN: let
The let statement declares a block scope local variable, optionally initializing it to a value.
Description
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Scoping rules
Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks . In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:
Carlos Chang Cheng
Courses Plus Student 12,030 PointsThanks!!
Benjamin Larson
34,055 PointsBenjamin Larson
34,055 PointsIn simple cases they will often have the same effect, but if you look through the examples on the MDN link you can see usages where it will make a difference. But essentially, it can be reassigned new values (as in a loop), unlike a constant, but it is limited to the scope of the block it is defined in. Declaring variables without var, let or const essentially makes them global variables (*not entirely true, but in most cases) so variables could accidentally be overwritten or deleted elsewhere in your code. Using
letis a way to be explicit about it's usage and prevent bugs in your code.