var, let, const
One of the first features you may have noticed in ES6 is a new way to declare variables (and now constants) with let
and const
instead of just var
.
These new keywords are used to create Block Scoped variables and constants.
Variable declarations with var
were only capable of Global Scope and Function Scope
All three keywords are capable of Global Scope
Keyword Behavior
Below is a table you can quickly reference explaining the differences. If you are looking for a recommendation for which ones to use in what scenarios here is my recommendation:
- Avoid using
var
- Use
const
wherever possible - When you have a variable you expect will change over time use
let
Keyword | Scope | Redefinable | Redeclarable | Hoisting |
---|---|---|---|---|
var | function | ✅ | ✅ | ✅ |
let | block | ✅ | ❌ | ❌ |
const | block | ❌ | ❌ | ❌ |
Function Scope
Notice in the following code snippet we can access all of the variables from within the function.
Now that we have moved the log statements outside of the function you'll see we end up with a reference error.
Block Scope
In the following example var1
will be accessible outside of the if
statement which is considered a block. Both let
and const
will be confined to the if
block.
Redefining keywords
You will be able to redefine variables declared with var
.
You will also be able to redefine variables declared with let
.
This should go without saying but you can't redefine a constant declared with const
it will throw a type error.