I did the last Javascript course Codecademy had, and their jQuery course.
I wanted to do this new course to get up-to-date on Javascript syntax.
Now, I’m hearing that var, one of the things that I used most, is not to be used! What’s up with that?
Now, I’m supposed to use const and let. Const seems like it could be helpful, but let? That just seems like a bad replacement for var. var and const actually stand for what they are, but let? It seems to stand for nothing!
Codecademy doesn’t say what it stands for.
Can somebody please tell me the problem with var? And also please tell me what let stands for.
the new courses teaches es6, here is a good answer about var:
this becomes very clear when we start using loops:
for (let i = 0; i < 5; i++){
console.log(i)
}
console.log(i)
and:
for (var i = 0; i < 5; i++){
console.log(i)
}
console.log(i)
in the first code, using let, i only exist inside the loop (block scope, only exist within the loop block) where as var (second code example) has a function scope (it still exist after loop block, even though it would make sense that i only exist inside the loop (block)
The first example uses let to define the variable i. The expected behavior is that you are declaring the i variable to act as an index or loop counter within the for loop only. Therefore, you’d want that variable to only work within that for code block, meaning within the for curly braces.
Does that make sense?
Why use let instead of var?
It makes our code more readable and predictable. We are declaring that this variable has this specific scope, i.e. where we defined it.
Think of it as let this variable represent this value. You use it to declare a variable with a given block scope.
When to Use let vs. const
Use let anytime you need to change what is assigned to it, as that changes it’s identifier in memory. Good examples are the for loop above, strings, etc. where what is assigned to it may change within that scope.
Use const when what’s assigned to it will not change. Don’t get confused here, as const is mutable. Good examples are objects, arrays, and function expressions assigned. What is within the object or array may change, but the identifier to a specific object instance or array will not change.