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.
Many people are confused, thinking that const makes an object immutable. In fact, const works differently.
Const protects the variable, not the object:
const user = { name: 'John' };
user.name = 'Peter'; // Allowed — modifying properties
user = {}; // Not allowed — error! Can't reassign variableconst obj = { a: 1 };
obj.a = 2; // Modification — allowed
obj.b = 3; // Addition — allowedconst obj = { a: 1 };
obj = { b: 2 }; // Reassignment — not allowed! Errorconst user = { name: 'John', age: 25 };
// All these operations are allowed
user.name = 'Peter';
user.age = 30;
user.city = 'Moscow';
delete user.age;const user = { name: 'John' };
// This will cause an error
user = { name: 'Peter' }; // TypeError!const arr = [1, 2, 3];
arr.push(4); // Allowed — modifying array
arr = []; // Not allowed — error!const obj = { a: 1 };
// obj always points to the same object in memoryconst config = { theme: 'dark' };
// Can update settings
config.theme = 'light';
config.lang = 'en';
// But can't accidentally overwrite entire config
// config = {}; // This protects from errorconst api = {
baseUrl: 'https://api.example.com'
};
// Can add methods
api.getUsers = function() { /* logic */ };
// But can't replace entire api
// api = {}; // Error!// ❌ 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// ❌ Error — can't reassign const
const obj = { a: 1 };
obj = { b: 2 }; // TypeError!
// ✅ Proper way to change content
obj.a = 2; // Modify propertiesUnderstanding 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 💪