How to Deep-Freeze an Object in JavaScript?
Last Updated :
15 Mar, 2025
In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutability at all levels, you need a deep freeze function.
What is Object.freeze() in JavaScript?
Before diving into deep freezing, let's understand the behavior of Object.freeze():
- Object.freeze() is a built-in JavaScript method that prevents any changes to an object.
- It applies only to the top-level properties of an object.
- Nested objects or arrays are not frozen, meaning they can still be modified.
Example of Shallow Freeze Using Object.freeze()
Object.freeze() prevents modification of the top-level properties, however, it does not freeze nested objects or arrays:
JavaScript
const obj = {
key1: "value1",
key2: ["value2", "value3"]
};
Object.freeze(obj);
obj.key2[0] = "newValue";
console.log(obj);
Output{ key1: 'value1', key2: [ 'newValue', 'value3' ] }
What is Deep-Freezing?
Deep-freezing is the process of recursively applying Object.freeze() to every nested object or array. This ensures that the entire structure, including nested properties, is immutable.
In simple terms, deep-freezing ensures that:
- You can't modify the top-level properties.
- You can't modify any properties inside nested objects or arrays.
- The entire object becomes read-only.
How to Implement Deep-Freeze in JavaScript?
Now, let's look at how to implement deep-freezing manually in JavaScript. We'll write a deepFreeze() function that will recursively freeze an object and all nested objects or arrays within it.
Steps to Implement Deep Freeze:
- Check if the value is an object: Only objects and arrays can be frozen, so we'll need to check if a value is an object before trying to freeze it.
- Recursively freeze nested objects: If an object has a property that is itself an object, we'll call the deepFreeze() function recursively.
- Freeze the current object: Once all properties are frozen, apply Object.freeze() to the current object.
Code Example: Deep Freeze Function
JavaScript
const deepFreeze = (obj) => {
if (obj === null || typeof obj !== "object") {
return obj; // Exit if not an object or is null
}
// Recursively freeze properties (including arrays)
Object.keys(obj).forEach((key) => {
deepFreeze(obj[key]);
});
return Object.freeze(obj); // Freeze the current object
};
// Test cases
const obj1 = {
key1: "value1",
key2: {
nestedKey: "nestedValue",
},
key3: ["val3", "val4", "val5"], // Array inside object
};
const deepFrozenObj = deepFreeze(obj1);
console.log("Before Change:");
console.log(deepFrozenObj);
try {
deepFrozenObj.key3[0] = "newValue"; // Throws an error in strict mode
} catch (e) {
console.error(`Error: ${e.message}`);
}
console.log("After Change:");
console.log(deepFrozenObj);
OutputBefore Change:
{
key1: 'value1',
key2: { nestedKey: 'nestedValue' },
key3: [ 'val3', 'val4', 'val5' ]
}
After Change:
{
key1: 'value1',
key2: { nestedKey: 'nestedValue' },
key3: [ 'val3', ...
In this example:
- if (obj && typeof obj === "object"). We check that obj is not null and is indeed an object (arrays are also considered objects in JavaScript).
- If the property is an object (or array), we recursively call deepFreeze() on that property. This ensures that all nested objects and arrays are frozen.
- After ensuring that all nested objects are frozen, we freeze the current object using Object.freeze().
Why Do You Need Deep Freeze?
Deep-freezing is crucial when you need to ensure that no part of an object can be changed, including its deeply nested elements. This is particularly useful in scenarios like:
- Immutable data structures: To maintain a reliable and consistent state, especially in environments like React or Redux.
- Data integrity: When handling complex data models, you may want to prevent any accidental modifications.
- Security: In environments where data must remain constant to prevent malicious changes.
Alternatives to Deep-Freeze
While deepFreeze() is a great solution for deep immutability, there are other ways to handle immutability:
- Libraries: Libraries like Immutable.js or immer are designed to handle immutable data structures, and they handle deep freezing and immutability automatically.
- Object.assign() / Spread operator: These techniques can be used to create shallow copies of objects, but they do not offer deep immutability on their own.
Similar Reads
How to Compare Objects in JavaScript? Comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations. Below are the various approaches to co
3 min read
How to Deep clone in JavaScript? Deep clone in JavaScript refers to creating a complete copy of an object, including all nested objects, ensuring that changes to the cloned object do not affect the original. Unlike shallow cloning, deep cloning requires copying all levels of the objectâs structure.1. Using Spread Operator to Deep C
2 min read
How to Create Dynamic Values and Objects in JavaScript? In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and
3 min read
How to Store an Object Inside an Array in JavaScript ? Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read
Difference between Object.freeze() and const in JavaScript ES6 has brought several new features and methods into JavaScript since its release. Amongst these new features are Object.freeze() method and const. Sometimes people get confused between Object.freeze() method and const but the Object.freeze() and const are completely different. In this article we w
3 min read
How to Store an Object sent by a Function in JavaScript ? When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
2 min read
How to Set Time Delay in JavaScript? Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
How to Create Enums in JavaScript ? An enum, short for "enumerated type", is a special data type in programming languages that allows us to define a set of named constants. These constants are essentially unchangeable variables that represent a fixed collection of possible values. Each contants can be accessed by its name. Enums are v
4 min read
How to add and remove properties from objects in JavaScript ? We will try to understand how to add properties to an object and how to add or remove properties from an object in JavaScript.Before we go and see the addition and removal of properties from an object let us first understand the basics of an object in JavaScript.Object:An object in JavaScript is a c
6 min read