How to make an object unchangeable
Short answer
Object.freeze() forbids adding, changing and removing properties. Attempts to change it are ignored:
const config = Object.freeze({ apiUrl: '/api', retries: 3 });
config.retries = 10;
console.log(config.retries);
console.log(Object.isFrozen(config));Output:
3
trueNested objects
The freeze is shallow: nested objects stay changeable. Freeze them with a recursive function:
const deepFreeze = (object) => {
for (const value of Object.values(object)) {
if (typeof value === 'object' && value !== null) deepFreeze(value);
}
return Object.freeze(object);
};
const config = deepFreeze({ db: { host: 'localhost' } });
config.db.host = 'example.com';
console.log(config.db.host);Output:
localhostCommon mistake
const forbids only assigning a new value to the variable. The object itself can still be changed:
const user = { name: 'Anna' };
user.name = 'Oleg';
console.log(user.name);Output:
OlegFunctions used in this recipe
- Object.freeze — Prevents any changes to an object.
- structuredClone — Creates a deep copy of an object with all nested data.