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
Joseph Frazer
5,404 PointsLet vs. Var
Whats the difference?
2 Answers
Alexander Davison
65,469 Points I had this question before, and I got a fantastic answer (from Andren):
Let creates a block-scoped variable, this means that if lets say you had a while loop and within that while loop you defined a variable called "test" using let, that variable would only exist within the while loop code block. It would not be accessible from outside the while statement. If you created said variable using var instead, then the variable would be accessible from anywhere in the function even though it was defined within the while loop.
That is how variable scopes work in most other programming languages by default. So let is basically just a version of var that fixes the fact that JavaScript variables by default has a function scope regardless of where in the function they are defined, which has often been criticized as a fault of the language.
However other than the scope of the variable a "var" variable and a "let" variable act the same, they can both be reassigned whenever you want, neither of them are a constant.
Answer made by Andren
I hope this post helps you out :)
~Alex
Umesh Ravji
42,386 PointsYou might want to look at this course, it would probably describe things better than I could :)
https://teamtreehouse.com/library/defining-variables-with-let-and-const