Use-Cases of this tutorial
- Know how to make an immutable object / array with native Javascript.
- Know about the Object.freeze() method.
- Know whether a given object is frozen or not.
- Know how to catch the error when attempt is made to update a frozen object.
The Object.freeze() method can make an object or array immutable. No changes can be made to that object once it gets immutable.
If multiple developers are working on a Javascript application, it is very common that variables and data created by one developer may be passed to another developer. The other developer, knowingly or unknowingly, may modify the original data passed to him. Depending on the case, it may result in a bug.
To prevent such situations, the original developer needs to make his data immutable — it cannot be changed. Even if the other developer tried to change the original data, it would result in an error. This should be the ideal behaviour.
For such cases, Javascript has the Object.freeze() method. Like the name suggests, when used on an object, it freezes it. No new properties can be added, values of existing properties cannot be changed, and existing properties cannot be removed.
var sample = {
id: 1003,
name: "John",
age: 35
};
// allowed
sample.age = 34;
// object is now frozen
Object.freeze(sample);
// this will not change value
sample.age = 30;
// "34"
console.log(sample.age);
Knowing whether an Object is Frozen or Not
The Object.isFrozen() method can check whether a specific object is frozen or not. If frozen, it returns a boolean true, and false otherwise.
var sample = {
a: 23
};
// false
console.log(Object.isFrozen(sample));
Object.freeze(sample);
// true
console.log(Object.isFrozen(sample));
Catching Error if Attempt is Made to Change a Frozen Object
By default, changing a frozen object will fail silently, without throwing an error.
However if the code is running in strict mode, then a TypeError exception will be thrown. This exception can be caught, and we can come to know that the object cannot be changed.
var sample = {
a: 23
};
Object.freeze(sample);
// will fail silently
sample.a = 50;
"use strict";
var sample = {
a: 23
};
Object.freeze(sample);
// exception will be thrown in strict mode
try {
sample.a = 50;
}
catch(error) {
// "a" is read-only
console.log(error.message);
}
Note : Object.freeze() Does a Shallow Freeze
Object.freeze() does a shallow freeze — only the immediate properties of the object cannot be changed. If the object contains another object as a property, then properties of that inner object can be changed even if the main object is frozen.
var sample = {
a: 23,
test: {
b: 45
}
};
Object.freeze(sample);
// won't happen
sample.a = 56;
// this will happen as "b" is the property of an inner object
sample.test.b = 100;
// "100"
console.log(sample.test.b);