Introduction
A object in javascript is immutable when its properties can’t be modified. To prevent accidental changes of objects, we need to ensure the immutability of objects. In javascript, we mainly use three functions - Object.freeze( ), Object.seal( ), Object.preventExtensions( ). Here we will limit our discussion to Object.freeze( ) function that preserves the enumerability, writability, configurability, and prototype of the object.
We will first discuss how Object.freeze( ) function works. Then we will see how these functions are used to make an object immutable.
What Object.freeze() does
In javascript, Object.freeze( ) function freezes an object. Freezing an object means preventing from new properties being added and existing properties from being removed. It also prevents changing the values of the existing properties of the object.
Object.freeze() method
Object.freeze( ) is one of the built-in object constructor static methods that prevents from removing or altering existing properties. It preserves the enumerability, writability, configurability, and prototype of the object by returning the passed object not its frozen copy.
Syntax
Object.freeze(obj)
Here, parameter obj is the object that needs to be frozen.
It returns the same object without making its copy.
Use cases
- This function is used to freeze objects and arrays.
- It is also used to make objects immutable.
Example
class Student
{
constructor(name, enr_no)
{
this.name=name;
this.enr_no=enr_no;
}
};
var student1 = new Student("Ninja",510519);
Object.freeze(student1); //frozen the object
student1.name = "Dhruv" //this assignment doesn’t affect
console.log(student1.name)
Output
Ninja //value of the name property is unchanged
Above example shows how value of the property is unaltered after freezing the object.
Freezing an array
var arr=[5,3,4,1]
Object.freeze(arr);
arr.push(2);
Output
TypeError: Cannot add property 4, object is not extensible