Overview
TL;DR
- const
- Has block scope, meaning it is only accessible within the block where it is declared.
- Cannot be reassigned to a new value, although objects and arrays can still be modified.
- Is hoisted but cannot be accessed before its declaration because of the TDZ.
- ✅ The best choice for most variables. Use it by default.
- let
- Also has block scope.
- Can be reassigned to a new value.
- Is also affected by the TDZ.
- ✅ Use it when you need to change a variable's value.
- var
- Has function scope, or global scope when declared outside a function.
- Can be reassigned and redeclared within the same scope.
- Is hoisted and initialized to undefined, so it does not have a TDZ.
- ⚠️ Avoid it in modern JavaScript because it can cause confusing bugs.
Scope
Example
Js
if (true) {
const a = 1;
let b = 2;
var c = 3;
}
console.log(typeof a); // "undefined"
console.log(typeof b); // "undefined"
console.log(c); // 3
Why?
- a and b are block-scoped, so they cannot be accessed outside the if block. Using typeof on these inaccessible identifiers returns "undefined" in this example.
- c is declared with var, so it is accessible outside the block.
Hoisting and the TDZ (Temporal Dead Zone)
- var is hoisted and initialized to undefined.
- let and const are hoisted but remain uninitialized until their declarations are evaluated.
- The period between entering the scope and evaluating a let or const declaration is called the Temporal Dead Zone (TDZ).
Example
Js
console.log(a); // undefined
var a = 1;
console.log(b); // ReferenceError
let b = 2;
console.log(c); // ReferenceError
const c = 3;
Why?
Reassignment vs. Mutation
Example
Js
const user = { name: "Alex" };
user.name = "Christian"; // Allowed: modifies the object
user = { name: "New" }; // TypeError: reassignment is not allowed
let count = 0;
count += 1; // Allowed: let permits reassignment
Freezing an Object
Js
const config = Object.freeze({
retries: 3,
});
// In strict mode, this throws a TypeError.
// In non-strict mode, the assignment is silently ignored.
config.retries = 5;
console.log(config.retries); // 3
Common Mistakes and How to Fix Them
1. Using var in Loops and Closures
Js
// ❌ Using var: outputs 3, 3, 3
var buttons = [0, 1, 2];
for (var i = 0; i < buttons.length; i++) {
setTimeout(() => console.log(i), 0);
}
// ✅ Using let: outputs 0, 1, 2
for (let j = 0; j < buttons.length; j++) {
setTimeout(() => console.log(j), 0);
}
2. Accessing Variables During the TDZ
Js
{
// console.log(greet); // ❌ ReferenceError (TDZ)
const greet = "hello";
console.log(greet); // ✅ "hello"
}
3. Redeclaring Variables
Js
var x = 1;
var x = 2; // ✅ Allowed, but potentially dangerous
let y = 1;
// let y = 2; // ❌ SyntaxError
const z = 1;
// const z = 2; // ❌ SyntaxError
Practical Usage Patterns
1. Prefer const
Js
const BASE_URL = "https://api.example.com";
const headers = {
"Content-Type": "application/json",
};
2. Use let When Necessary
Js
let attempts = 0;
while (attempts < 3) {
// Perform some work
attempts++;
}
3. Avoid var in Modern JavaScript
Quick Checklist
- Use const by default.
- Use let when reassignment is necessary.
- Avoid var in new code to reduce scope-related bugs.
- Remember the TDZ: do not access let or const variables before their declarations are evaluated.
- Remember that const prevents reassignment, not modifications to objects or arrays.
- Use Object.freeze() when you need to prevent changes to an object's own properties, keeping in mind that it is shallow by default.