Why can you modify fields of an object declared with const?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Objects #JS Basics

Brief Answer

The const keyword protects only the variable, not the object’s content. It prevents reassigning the variable to another object, but doesn’t prevent modifying the object’s properties. These are different operations.


Full Answer

Many people are confused, thinking that const makes an object immutable. In fact, const works differently.

What const Does

Const protects the variable, not the object:

const user = { name: 'John' };
user.name = 'Peter'; // Allowed — modifying properties
user = {}; // Not allowed — error! Can't reassign variable

Difference Between Modification and Reassignment

Property Modification

const obj = { a: 1 };
obj.a = 2; // Modification — allowed
obj.b = 3; // Addition — allowed

Variable Reassignment

const obj = { a: 1 };
obj = { b: 2 }; // Reassignment — not allowed! Error

Simple Examples

Can Modify

const user = { name: 'John', age: 25 };
 
// All these operations are allowed
user.name = 'Peter';
user.age = 30;
user.city = 'Moscow';
delete user.age;

Cannot Reassign

const user = { name: 'John' };
 
// This will cause an error
user = { name: 'Peter' }; // TypeError!

Important Features

1. Only Variable Protection

const arr = [1, 2, 3];
arr.push(4); // Allowed — modifying array
arr = []; // Not allowed — error!

2. Reference Doesn’t Change

const obj = { a: 1 };
// obj always points to the same object in memory

When This is Useful

Safe Data Work

const config = { theme: 'dark' };
 
// Can update settings
config.theme = 'light';
config.lang = 'en';
 
// But can't accidentally overwrite entire config
// config = {}; // This protects from error

Working with Functions

const api = { 
  baseUrl: 'https://api.example.com' 
};
 
// Can add methods
api.getUsers = function() { /* logic */ };
 
// But can't replace entire api
// api = {}; // Error!

Common Mistakes

1. Expecting Immutability

// ❌ Thinking object is frozen
const obj = { a: 1 };
obj.a = 2; // Works!
console.log(obj.a); // 2
 
// ✅ Proper understanding
console.log(obj.a); // 2 — object changed

2. Attempting Reassignment

// ❌ Error — can't reassign const
const obj = { a: 1 };
obj = { b: 2 }; // TypeError!
 
// ✅ Proper way to change content
obj.a = 2; // Modify properties

Simple Rules

  1. const — protects variable, not object
  2. Modification — can change object properties
  3. Reassignment — can’t change the variable itself
  4. Reference — variable always points to one object
  5. Safety — protects from accidental object replacement

Understanding how const works helps write more predictable code and avoid errors with variable reassignment.


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪