It does not have block scope. Therefore, it can lead to unpredictable behavior if you’re not careful (due to hoisting).
ES6 gave us 2 new ways to define variables, each of which has block scope. The key here is block scope.
What does block scope mean? Why is it important?
Look at the code that @stetim94 gave you above.
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?
let instead of
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 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.
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.