The Object.freeze function is utilized to freeze an object, thereby disallowing the addition of new properties to it. This method also restricts any alterations to the current properties, attributes, and their respective values.
Syntax:
Example
Object.freeze(obj)
Parameter
Obj : The object to freeze.
Return value:
This function delivers the object that was provided as an argument.
Browser Support:
| Chrome | 45.0 |
|---|---|
Edge |
12.0 |
| Firefox | 32.0 |
| Opera | No |
Example 1
Example
const object1 = {
property1: 22
};
const object2 = Object.freeze(object1);
object2.property1 = 33;
// Throws an error in strict mode
console.log(object2.property1);
Output:
Example 2
Example
const obj1 = { property1: 'freeze'};
const obj2 = Object.freeze(obj1);
obj2.property1 = 'new_data';
console.log(obj2.property1);
Output:
Output
" freeze "
Example 3
Example
var obj = { prop: function() {}, name: 'charry' };
console.log(obj);
obj.name = 'karri';
delete obj.prop;
console.log(obj);
var o = Object.freeze(obj);
obj.name = 'chris';
console.log(obj);
Output:
Output
[object Object] {
name: "charry",
prop: function() {}
}
[object Object] {
name: "karri"
}
[object Object] {
name: "karri"
}