Episode 2 of 11
Constants
Learn const — immutable variable bindings, block scoping, and when to use const vs let.
Constants
The const keyword declares a constant reference — a variable whose binding cannot be reassigned. It's the default choice for declaring variables in modern JavaScript.
Basic Syntax
const PI = 3.14159;
const API_URL = "https://api.example.com";
const MAX_RETRIES = 3;
console.log(PI); // 3.14159
Cannot Be Reassigned
const name = "Alice";
name = "Bob"; // ❌ TypeError: Assignment to constant variable!
const count = 10;
count = 20; // ❌ TypeError!
Once a const is assigned, you cannot reassign it to a different value.
Must Be Initialized
const age; // ❌ SyntaxError: Missing initializer in const declaration
// You MUST assign a value when declaring:
const age = 25; // ✅
Block Scoping
const is block-scoped — it only exists within the { } block where it's declared:
if (true) {
const message = "Hello";
console.log(message); // "Hello" ✅
}
console.log(message); // ❌ ReferenceError: message is not defined
var vs const — Scoping
// var is function-scoped (leaks out of blocks!)
if (true) {
var x = 10;
}
console.log(x); // 10 ← leaked! 😱
// const is block-scoped (stays contained)
if (true) {
const y = 10;
}
console.log(y); // ❌ ReferenceError ← safe! ✅
const with Objects and Arrays
Important: const prevents reassignment, not mutation. The contents of objects and arrays can be changed:
const user = { name: "Alice", age: 25 };
user.age = 26; // ✅ Works! Mutating the object is fine
user.email = "a@b.com"; // ✅ Adding a property is fine
user = { name: "Bob" }; // ❌ TypeError! Can't reassign the variable
const colors = ["red", "blue"];
colors.push("green"); // ✅ Mutating the array is fine
colors[0] = "orange"; // ✅ Changing an element is fine
colors = ["new", "array"]; // ❌ TypeError! Can't reassign
Making Objects Truly Immutable
const config = Object.freeze({
apiUrl: "https://api.example.com",
timeout: 5000,
});
config.timeout = 10000; // Silently fails (throws in strict mode)
console.log(config.timeout); // 5000 — unchanged
Object.freeze() prevents mutation. Combine with const for truly immutable data.
const in Loops
// ✅ Works with for...of (new variable each iteration)
const items = ["a", "b", "c"];
for (const item of items) {
console.log(item); // "a", "b", "c"
}
// ❌ Doesn't work with classic for loop (reassigns i)
for (const i = 0; i < 5; i++) { // TypeError on i++
console.log(i);
}
When to Use const
| Situation | Use |
|---|---|
| Value never changes | const ✅ |
| Reference to object/array (contents may change) | const ✅ |
| Loop variable that changes | let |
| Reassigned later | let |
Key Takeaways
constcreates a constant binding — cannot be reassigned- It's block-scoped, unlike
var(function-scoped) - Must be initialized at declaration
- Objects and arrays declared with
constcan still be mutated - Use
Object.freeze()for truly immutable objects - Default to
const— only useletwhen you need to reassign