const: Constant Bindings & Object MutationThe const keyword declares block-scoped constants. A const variable creates an immutable binding to a value, meaning the variable identifier cannot be reassigned. However, the value itself is NOT immutable if it holds an object or array.
flowchart TD
ConstDecl["const declaration"] --> TypeCheck{"Primitive or Reference?"}
TypeCheck -- "Primitive (Number, String, Boolean)" --> Prim["Value is completely immutable"]
TypeCheck -- "Reference (Object, Array)" --> Ref["Binding is fixed, but properties/elements remain mutable"]
Ref --> Freeze["Use Object.freeze() for deep immutability"]
const Behavioral Matrix| Data Type | Example Declaration | Reassignment (=) Allowed? |
Property / Element Mutation Allowed? |
|---|---|---|---|
| Primitive | const MAX = 100; |
No (TypeError) |
N/A (Primitives are immutable) |
| Array | const list = [1, 2]; |
No (TypeError) |
Yes (list.push(3)) |
| Object | const user = { id: 1 }; |
No (TypeError) |
Yes (user.name = "Alex") |
| Frozen Object | Object.freeze({ id: 1 }) |
No (TypeError) |
No (Throws error in strict mode) |
// Demonstrating const primitive binding vs object mutation
// 1. Primitive const binding
const APP_VERSION = "2.4.0";
// APP_VERSION = "2.5.0"; // Throws TypeError: Assignment to constant variable.
// 2. Mutable Array under const
const categories = ["Frontend", "Backend"];
categories.push("DevOps"); // Allowed: mutating contents of the reference
console.log("Mutated categories array:", categories);
// 3. Mutable Object under const
const dbConfig = {
host: "localhost",
port: 5432
};
dbConfig.port = 5433; // Allowed: mutating property value
console.log("Updated dbConfig:", dbConfig);
// 4. Truly Immutable Object using Object.freeze()
const immutableConfig = Object.freeze({
apiKey: "SECRET_KEY_12345",
environment: "production"
});
// In non-strict mode, this silently fails; in strict mode ('use strict'), throws TypeError
immutableConfig.environment = "staging";
console.log("Immutable Config (Environment unchanged):", immutableConfig.environment);
const by default unless you intend to reassign it later with let.const x; is invalid syntax and triggers a SyntaxError: Missing initializer in const declaration.Object.freeze() for Read-Only Constants: If an object constant must never be mutated by external code, wrap it in Object.freeze().What happens when you execute const colors = ["red", "blue"]; colors[0] = "green"; vs colors = ["green", "blue"];?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.