Monday, December 24, 2018

Understanding Object.freeze() in javascript

This tutorial explains how to freeze an object in javascript, so that object can't be modified further. The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed. The method returns the object in a frozen state.

Understanding Object.freeze() in javascript



Lets see the below example of Object.freeze() in javascript :

Example -1 : 

In this example, we are directly changing the employee object, once it get freeze using Object.freeze() function in javascript.
var employee = {
    name: "Sumit",
    age: 24
};

Object.freeze(employee);

//Changing the employee object directly
employee.name = "Skptricks"

console.log(employee)

Note : object value will not change, once it is freezed with the help of Object.freeze() function. Lets see the below output :

Output :
---------------------------
> Object { name: "Sumit", age: 24 }

Example -2 : 

In this example, we are directly changing the freeze object, in order to change the value of employee object.
var employee = {
    name: "Sumit",
    age: 24
};

const emp = Object.freeze(employee);

//Changing the emp object directly
emp.name = "Skptricks"

console.log(employee)

Note : object value will not change, once it is freezed with the help of Object.freeze() function. Lets see the below output :

Output :
---------------------------
> Object { name: "Sumit", age: 24 }

Example -3 :

In this example, we are using isFrozen function in order to check object is frozen or not in javascript. This function will return Boolean result.
True : Object is frozen.
False : Object is not frozen.
var employee = {
    name: "Sumit",
    age: 24
};

var salary = {
    name: "Sumit",
    salary: 2400
};

const emp = Object.freeze(employee);

// check object is frozen or not
console.log(Object.isFrozen(employee))
console.log(Object.isFrozen(salary))

Output :
---------------------------
> true
> false

This is all about Object.freeze() in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment