let and const
Fortunately there are two more keywords we can use to declare variables--let and const. Unlike var, variables that are declared with either let or const are not hoisted.
We can prove this by replacing our previous examples with both let and const. We saw that since var declarations are hoisted we can access variables before they are declared. Let’s first try out that same example with let:
console.log(age); let age = 26; // Uncaught ReferenceError: Cannot access 'age’ before initialization
And right away we get a reference error telling us that we can’t use a variable before it’s been initialized or created. Now let’s try this with const:
console.log(age); const age = 26; // Uncaught ReferenceError: Cannot access 'age’ before initialization
And we get the exact same error.
There’s actually a name for this behavior with let and const, when you try to use a let const variable before it exists, called the temporal dead zone.
Temporal dead zone (TDZ)
The temporal dead zone is just a complicated-sounding way of saying what we already understand, let / const variables are not hoisted unlike var. You can’t use a variable until it exists and this dead zone refers to the area between where a variable is attempted to be used and where it is actual declared. The variable is ‘dead’, meaning it doesn’t exist yet. It’s not more complex than that.
And since hoisting is no longer a thing, we are also going to get an error if we try to declare variables multiple times with the same name:
let age = 26; let age = 26; // Uncaught SyntaxError: Identifier 'age' has already been declared
let and const keywords replace var
So when do we use let versus const? In cases where a value is going to change, let is the best choice.
Only let can be declare and reassigned on separate lines, not const.
let age; age = 26;
However, if you try to create a const variable without initializing it, you will get an error:
const age; // Uncaught SyntaxError: Missing initializer in const declaration
So both let and const are both great replacements for var since they fix our hoisting problem, and in the next video we'll dive deeper into where each should be used.