Chapter II · Variables & Values

The const Keyword

The const keyword declares variables whose bindings cannot be reassigned after their initial creation.

01 What is const?

const stands for constant. It declares a block-scoped identifier whose reference cannot be reassigned once set. Crucially, const protects the binding, not necessarily the underlying value if that value is mutable (like an object or array).

Like let, const variables are subject to the Temporal Dead Zone and must be initialized immediately upon declaration.

02 Simple Example

Declaring a constant value and attempting reassignments.

const.js
const API_URL = "https://api.example.com";
// API_URL = "https://new.com"; -> TypeError!

const user = { name: "Alice" };
user.name = "Bob"; // Allowed! Mutating object properties
console.log(user.name); // "Bob"

Reassigning API_URL throws an error, but mutating properties inside a const object is fully permitted.

03 How It Works

The engine enforces immutability on the pointer reference itself, throwing a TypeError if any subsequent assignment operator targets the constant identifier.

score identifier 10 value in memory binds to let score = 10; — the name and the value are linked, not fused.

Const locks the variable identifier to its initial memory reference permanently.

04 Step-by-Step

  1. The engine encounters a const declaration.

  2. An initial value must be supplied immediately or a SyntaxError occurs.

  3. The identifier is bound permanently to that memory reference.

  4. Any attempt to reassign the identifier later triggers a TypeError.

05 Mental Model

"A locked mailbox where you can drop something in once, but can never replace the box itself."

The connection is permanent, even if items inside a container box can still be rearranged.

06 Common Mistakes

Believing const makes objects immutable. It doesn't — const user = { name: "Alice" }; user.name = "Bob"; works fine. If you need a truly frozen object, use Object.freeze(user) (shallow) in addition to const.

Best practice: use const for array and object bindings too, even though you'll still push/mutate their contents — it communicates "this variable will always refer to the same array/object," which is usually what you mean.

07 Interview Questions

Q: Can you mutate an object declared with const?

Yes — const only prevents reassigning the variable binding itself; the object's properties can still be changed. Only the reference is frozen, not the value.

Q: Should you always default to const?

Most style guides recommend it — reach for let only when a variable genuinely needs reassignment, since it signals intent and prevents accidental overwrites.

Key Takeaway

The const keyword creates read-only variable bindings that prevent accidental reassignments throughout your codebase.

Related Concepts