Object.freeze()
Object.freeze()
will prevent an object from being modified. Once we freeze an object, we:
This method returns the object, at which the freeze
method is called.
let user = {name : "John",age : 20}let frozenUser = Object.freeze(user);// addfrozenUser.profession = "doctor 👨⚕️ ";console.log("After adding new property ", frozenUser); // {name: "John", age: 20}// deletedelete frozenUser.name;console.log("After deleting name property ", frozenUser); // {name: "John", age: 20}// modifyfrozenUser.name = "Raj";console.log("After modifying name property ", frozenUser); // {name: "John", age: 20}// change enumerable propertytry{Object.defineProperty(frozenUser, 'name', {enumerable : false});//throws an error cannot redefine property} catch(e){console.log("Error on changing enumerable to false");}//bothe the user object and frozen object points to same objectconsole.log(frozenUser === user); // true
All the operations above will throw a TypeError exception in strict mode.
We can also freeze an array.
let array = [1,2,3,4,5]let frozenArray = Object.freeze(array);frozenArray[0] = 10;console.log(frozenArray); // [1,2,3,4,5]
When we try to add or remove a value, it will throw a TypeError.
The object freeze method does a shallow freeze, meaning that if the values of properties are objects themselves, those objects are not frozen.
let user = {
name : "John",
address : {
doorNo : 20
}
}
Object.freeze(user);
The above code will prevent the addition, deletion, and modification of a property to the user
object; but, the freeze will not be applied to the address
property of the user
object (i.e., we can change the address object) because the address
property is an object itself .
let user = {name : "John",address : {doorNo : 20}}let frozenObject = Object.freeze(user);user.address.doorNo = 100;user.address.street = "First Street";console.log("After changing address", user.address); // {doorNo: 100} // {doorNo: 100, street: "First Street"}
If you want to completely freeze your object:
function deepFreeze(object) {// Retrieve the property names defined on objectvar propNames = Object.getOwnPropertyNames(object);// Freeze properties before freezing selffor (let name of propNames) {let value = object[name];object[name] = value && typeof value === "object" ?deepFreeze(value) : value;}return Object.freeze(object);}let user = {name : "John",address : {doorNo : 20}}let frozenObject = deepFreeze(user);user.address.doorNo = 100; // no changes will be doneuser.address.street = "First Street"; // no changes will be doneconsole.log("After changing address", user.address);
We can use the isFrozen
method to check if an object is in the frozen state:
let obj = {name : "John"}console.log("Before freeze isFrozen = ", Object.isFrozen(obj) );Object.freeze(obj);console.log("After freeze isFrozen= ", Object.isFrozen(obj) );
Free Resources