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

JavaScript

What's the difference between "let" and "const" in JavaScript?

^

^

^

^

^

What's the difference? I saw Guil use "let" in a for loop like this:

for (let i = 0; i < 10; i++) {
    // Some code
}

And also use "const" in the same script.

Can someone explain the differences?

I learned that "let" was for making constants in the Swift Basics course.

Thanks! alex

1 Answer

Your knowledge of Swift might actually cause more confusion in this case than if you had no knowledge of it. In JavaScript let does not have the same meaning as it does in swift.

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.

A const variable is essentially what you would think of as a "let" variable from swift, it is a constant which cannot be reassigned after it has been created, and it needs to be assigned a value when you declare it.

One caveat of const though is that if you assign something to it that is a reference type value like an object for instance, then you can still modify the contents of said object. You just can't go and set the variable to a different object or value after it is defined.

If there is still something you are contused about, or you found a part of my explanation unclear. Then please feel free to ask followup questions, I'll be glad to answer any questions you might have.

Thanks for clarifying the differences :)

Really did help!

Now I understand the differences and can write more efficient programs.