How to Freeze Object in JavaScript: Syntax and Examples
Use
Object.freeze(object) to make an object immutable in JavaScript. This method prevents adding, deleting, or changing properties of the object.Syntax
The syntax to freeze an object is simple:
Object.freeze(object): Takes the object you want to freeze as an argument.- Returns the same object but now immutable.
javascript
const frozenObject = Object.freeze(object);
Example
This example shows how freezing an object stops changes to its properties:
javascript
const user = { name: 'Alice', age: 25 }; Object.freeze(user); user.age = 30; // This will not change the age user.city = 'New York'; // This will not add a new property console.log(user);
Output
{"name":"Alice","age":25}
Common Pitfalls
Freezing only works on the object itself, not on nested objects inside it. Also, Object.freeze() is shallow, so nested objects can still be changed.
Trying to modify a frozen object in strict mode throws an error, but in non-strict mode it fails silently.
javascript
const person = { name: 'Bob', address: { city: 'Paris' } }; Object.freeze(person); person.address.city = 'London'; // This change works because address is not frozen console.log(person.address.city); // Outputs: London
Output
London
Quick Reference
- Object.freeze(obj): Makes
objimmutable (shallow). - Does not freeze nested objects.
- Returns the frozen object.
- Use
Object.isFrozen(obj)to check if frozen.
Key Takeaways
Use Object.freeze() to make an object immutable and prevent changes.
Freezing is shallow; nested objects remain mutable unless frozen separately.
Modifying a frozen object fails silently in non-strict mode and throws in strict mode.
Check if an object is frozen using Object.isFrozen().
Freezing helps protect objects from accidental changes in your code.