var, let and const.
Hoisting and the temporal dead zone. The usual answer is that var is global and let is block scoped, and that is not the whole answer.
Let's take one of the most common JavaScript questions. Everyone knows the short answer: var is "global" and let and const are block scoped.
But is that the whole answer? What about variables inside a function, or in a setTimeout? Can we use them before we declare them? And why do we still have var if let does everything?
To see the difference properly, we need to look at how JavaScript reads code before it runs it.
Hoisting
var a = 10;
let b = 20;
console.log(a); // 10
console.log(b); // 20Before running anything, the engine goes through the scope, finds every declaration and sets aside memory for it. This is called hoisting. Functions are hoisted too.
Now move the logs above the declarations.
console.log(a); // undefined
console.log(b); // ReferenceError: Cannot access 'b' before initialization
var a = 10;
let b = 20;a is undefined. For b we get an error, and the error is telling: it does not say b is not defined. It says we cannot use it yet.
Both declarations were hoisted. The difference is what they were given.
- A
varis created and set toundefinedat the top of its scope. So it can be read early, and you getundefined. - A
letorconstis created but left uninitialised. It only gets a value when the line that declares it actually runs.
The temporal dead zone
Take each of these logs on its own:
console.log(a); // undefined
console.log(b); // ReferenceError
var a = 1;
console.log(b); // ReferenceError
let b = 0;
console.log(b); // 0From the start of the scope until the line let b = 0 runs, b exists but cannot be touched. That stretch is called the temporal dead zone, or TDZ. After the declaration line, b works normally.
Function scope and block scope
Now the part about scope. A block is anything between { and }.
A variable declared with var:
- outside any function, is available in the global scope;
- inside a function, is available everywhere in that function.
A variable declared with let is available only inside the block where it is declared.
Inside a plain function the two look the same. Neither can be read from outside.
function withVar() {
var x = 1;
}
console.log(x); // ReferenceError: x is not defined
function withLet() {
let y = 1;
}
console.log(y); // ReferenceError: y is not definedSo where is the difference? A loop shows it.
function countWithVar() {
for (var i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
console.log("after the loop:", i); // after the loop: 5
}
function countWithLet() {
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
console.log("after the loop:", i); // ReferenceError: i is not defined
}With var, i is still there after the loop, though still not outside the function. With let, i belongs to the loop's block and is gone when the loop ends.
It is not about the loop. Any pair of braces does the same.
function blocks() {
{
var fromVar = "var";
let fromLet = "let";
}
console.log(fromVar); // "var"
console.log(fromLet); // ReferenceError: fromLet is not defined
}So var ignores blocks and belongs to the whole function it is in (or to the global scope if it is not in a function). That is why it is more accurate to call var function scoped than global. let belongs to the nearest block.
Redeclaration
The third difference: with var you can declare the same name twice in one scope. With let you cannot.
var city = "Jaipur";
var city = "Bangalore"; // fine
let town = "Jaipur";
let town = "Bangalore"; // SyntaxError: Identifier 'town' has already been declaredconst
const behaves like let, with one more rule: it must be given a value when it is declared, and it cannot be assigned again.
const limit = 5;
limit = 6; // TypeError: Assignment to constant variable.In short
letandconstare block scoped, cannot be used before their declaration runs, and cannot be redeclared in the same scope.constalso cannot be reassigned.varis function scoped, can be read before its declaration (asundefined), and can be redeclared.
There is more to say about how these behave inside setTimeout, closures and IIFEs, but the three ideas above are underneath all of it.
Further reading: let on MDN.