Why Object.freeze ?
Object.freeze () is a method used to freeze an object. A frozen object does not change. That is, the properties available on the Object.freeze () object do not change. New features cannot be added from the outside. Object.freeze () protects the object’s enumeration, configurability, writability, and prototype. Returns the forwarded object and does not create a frozen copy.
Syntax:
Object.freeze(obj)
obj : It is the object which has to be freezed.
The values for the data properties of a frozen object cannot be changed, writeable, and configurable.
Let it be an array in the object. If we freeze this object with Object.freeze (), we cannot add or remove elements to the array. So it’s frozen on the array.
For example; We have an object named person. Let’s enter a value in this object. (Name). Then add different conditions with the help of “if”.
let person = {
name: "Rick"
};
function control(firstname) {
if (firstname.name == "Rick")
console.log("his name is Rick");
else
console.log("this is" + firstname.name);
};
control(person);
console.log(person);
output:
his name is Rick
{name: “Rick”}
Object.freeze () is used if we do not want the object to change its name:
let person = {
name: "Rick"
};
Object.freeze(person);
person.name = "alex";
function control(firstname) {
if (firstname.name == "Rick")
console.log("his name is Rick");
else
console.log("this is" + firstname.name);
};
control(person);
console.log(person);
output:
his name is Rick
{name: “Rick”}
In general, the Object.freeze () method does this:
- Object.freeze() is used for freezing objects and arrays.
- Object.freeze() is used to make an object immutable.
JavaScript Object.freeze Examples
Example 1
let numbers = {
x: 1,
y: 2,
z: 3,
};
Object.freeze(numbers);
numbers.x = 3;
numbers.y = 2;
numbers.z = 1;
console.log(numbers)
output:
{x: 1, y: 2, z: 3}
Example 2
let myObject = {
func: 10,
x: {
value: 20,
}
};
Object.freeze(myObject);
myObject.func = 100;
myObject.x.value = 100;
console.log(myObject)
output:
func: 10, x: {…}}
func: 10
x: {value: 100}
Example 3
let obj = {
foo: "foo",
list: [1, 2, 3],
bar: {
foo: "truecodes.org"
}
};
Object.freeze(obj);
obj.foo = "foo2";
obj.list = [4,5,6];
console.log(obj)
output:
bar: {foo: “truecodes.org”}
foo: “foo”
list: [1, 2, 3]
Example 4
let obj = {
func: function () { },
foo: "foo"
};
Object.freeze(obj);
obj.foo = "foo2";
delete obj.func;
console.log(obj);
output:
{func: ƒ, foo: “foo”}
Browser Support
| Chrome | 6 |
| Edge | yes |
| Firefox | 4 |
| Internet Explorer | 9 |
| Opera | 12 |
| Safari | 5.1 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 4 |
| Opera Android | 11.5 |