Object.freeze vs Object.seal in JavaScript

To make an object immutable, you can use Object.freeze(), or to prevent adding or removing properties, you can use Object.seal().

Object.freeze();

This method makes the object completely immutable.

const obj = Object.freeze({ name: 'John' });

obj.name = 'David';  // This change won't happen
console.log(obj.name);  // 'John' (unchanged)

Result: The name property cannot be changed.

Object.seal();

This method prevents adding new properties and deleting existing ones, but you can still change the values of the existing properties.

const obj = Object.seal({ name: 'John' });

obj.name = 'David';  // This change is allowed
obj.age = 30;  // New property cannot be added
delete obj.name;  // Property cannot be deleted

console.log(obj.name);  // 'David' (changed)
console.log(obj.age);   // undefined (not added)

Result: The name can be changed, but age can't be added or name deleted.

Buy Me A Coffee

Explore More Posts