Home >Web Front-end >JS Tutorial >Mastering Object.freeze() and Object.seal() in JavaScript: Controlling Object Mutability
When working with objects in JavaScript, controlling their mutability is essential to prevent unintended changes. Two methods provided by JavaScript for this purpose are Object.freeze() and Object.seal(). Understanding their differences and use cases is key to writing robust code.
The Object.freeze() method makes an object immutable. This means:
Object.freeze(obj);
const obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 }
Use Object.isFrozen() to determine if an object is frozen:
console.log(Object.isFrozen(obj)); // true
The Object.seal() method restricts modifications to an object but is less strict than Object.freeze(). It allows:
Object.seal(obj);
const obj = { name: "Bob", age: 30 }; Object.seal(obj); obj.age = 35; // Allowed: Existing properties can be modified obj.gender = "male"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Bob", age: 35 }
Use Object.isSealed() to determine if an object is sealed:
Object.freeze(obj);
Feature | Object.freeze() | Object.seal() | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Add new properties |
|
Not allowed |
||||||||||||||||||
Remove existing properties | Not allowed | Not allowed | ||||||||||||||||||
Modify existing properties | Not allowed | Allowed | ||||||||||||||||||
Reconfigure property descriptors | Not allowed | Not allowedconst obj = { name: "Alice", age: 25 }; Object.freeze(obj); obj.age = 30; // Does nothing (strict mode: throws an error) obj.gender = "female"; // Does nothing (strict mode: throws an error) delete obj.name; // Does nothing (strict mode: throws an error) console.log(obj); // { name: "Alice", age: 25 } |
||||||||||||||||||
Use case | Immutable objects (constants) | Restrict structure but allow value changes |
console.log(Object.isFrozen(obj)); // true
Prevent Confusion with Object Mutability: Clearly document when and why an object is frozen or sealed to avoid misinterpretations in team environments.
Seal Before Freezing
The above is the detailed content of Mastering Object.freeze() and Object.seal() in JavaScript: Controlling Object Mutability. For more information, please follow other related articles on the PHP Chinese website!