Freezing JavaScript objects with Object.freeze()

In JavaScript, objects are used to store keyed collections of various data and more complex entities. Objects penetrate almost every aspect of the JavaScript language.

The object might be accessed as global or passed as an argument. Functions that have access to the object can modify the object, whether intentionally or accidentally. To prevent modification of our objects, one of the techniques is to use Object.freeze(). This method prevents the modification of existing property attributes and values, and prevents the addition of new properties.

Ok, why would I need to freeze an object?

Freezing an object can be useful for representing a logically immutable data structure, especially if changing the properties of the object could lead to bad behavior elsewhere in your application.

Let’s see an example:

var employee = {

name: "John Doe",

role: "Developer"

};

Object.freeze(employee);

(function() {

"use strict";

// TypeError: Can't modify property role

employee.role = "Tester";

})();

Since we have added strict mode, we will see the error as shown below.

Screen Shot 2017-04-16 at 22.44.05

Let’s see another example:

var employee = {

name: "John Doe",

role: "Developer"

};

Object.freeze(employee);

(function() {

"use strict";

// TypeError: Can't add property department, object is not extensible

employee. department= "IT";

})();

And the output would be as follows:

Screen Shot 2017-04-16 at 22.47.39

Object.freeze method takes an object and renders it immutable. In the example above, the employee object remains safe from modification and available for later use.

If you don’t want to throw errors all over the place, JavaScript provides another method Object.isFrozen() to detect whether the object is frozen.

var employee = {

name: "John Doe",

role: "Developer"

};

Object.freeze(employee);

if (Object.isFrozen(employee)) {

alert("employee is frozen!");

}

And you will see the result as follows:

Screen Shot 2017-04-16 at 21.26.04

Note that Object.freeze is shallow, so you’d need to recursively apply it on nested objects to protect them. This feature is part of the ECMAScript 5 specification, which means it isn’t available in older browsers like IE8 and below.

One thought on “Freezing JavaScript objects with Object.freeze()

Comments are closed.