Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
true

Nested 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:

localhost

Common 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:

Oleg

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.