How to freeze an object in JavaScript

Preventing object modifications is crucial for maintaining data integrity and avoiding unintended side effects in JavaScript applications. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve found that immutable objects are essential for building reliable applications. The most effective way to make an object immutable is using the Object.freeze() method. This approach ensures that no properties can be added, removed, or modified after freezing.

Use Object.freeze() to make an object completely immutable.

const user = { name: 'John', age: 30 }
const frozenUser = Object.freeze(user)

The Object.freeze() method prevents any changes to the object’s properties. Once frozen, you cannot add new properties, delete existing ones, or modify property values. The method returns the same object that was passed in, now in a frozen state. Any attempts to modify a frozen object in strict mode will throw a TypeError, while in non-strict mode they will simply be ignored.

Best Practice Note:

This is the same approach we use in CoreUI components to protect configuration objects from accidental modifications. Note that Object.freeze() creates a shallow freeze - nested objects remain mutable unless they are also frozen individually.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author