What is const?
const is a keyword introduced in ES6 (ECMAScript 2015) that allows you to declare block-scoped constants — variables that cannot be reassigned after they’re initialized.
const name = "Alice";
name = "Bob"; // ❌ TypeError: Assignment to constant variable
🔹 Key Characteristics of const
✅ Must be initialized at declaration You must assign a value when declaring a
const.const city = "New York"; // ✅ const state; // ❌ SyntaxError🚫 Cannot be reassigned Once declared, the variable binding cannot be changed.
const age = 30; age = 35; // ❌ Error🧠 Does NOT make objects/arrays immutable You can still change the contents of a
constobject or array — but not reassign the variable itself.const person = { name: "Alice" }; person.name = "Bob"; // ✅ Allowed person = {}; // ❌ Error
🔹 const vs let vs var
Feature |
|
|
|
|---|---|---|---|
Scope | Block | Block | Function |
Hoisting | No (TDZ) | No (TDZ) | Yes |
Reassignable | ❌ No | ✅ Yes | ✅ Yes |
Redeclarable | ❌ No | ❌ No | ✅ Yes |
🔸 TDZ = Temporal Dead Zone (can't access before declaration)
🔹 When to Use const
Use const by default unless you know the value will change. This encourages immutable code, which helps prevent bugs and makes your code easier to reason about.
✅ Best for:
Configuration values
Fixed references (functions, objects)
Preventing accidental reassignment
🔹 Real-Life Example
const API_KEY = "abc123";
const user = {
name: "Jane",
loggedIn: true
};
// Modify object properties
user.loggedIn = false; // ✅
🔚 Conclusion
Using const in JavaScript is a great way to write clearer, more predictable code. It doesn’t make values immutable — but it does lock the variable’s reference, which is incredibly useful for maintaining consistency in your applications.
Pro Tip: Start with const, use let only when you know reassignment is needed. Avoid var in modern codebases.