The Object freeze() method is used to freeze an object. A frozen object becomes immutable, as it prevents the addition, deletion, or modification of its properties.
This can be helpful when creating a constant object with a fixed set of properties.
Syntax
Object.freeze(obj)
Parameters
obj: It refers to the object that will be frozen.
Return value
Returns object that was passed to the function.
Visual Representation
Example 1: How to Use Object.freeze() method
let student = { name: 'KRUNAL', education: 'BE IT' };
let freezedObj = Object.freeze(student);
freezedObj.name = 'ANKIT'; // This will have no effect on the object
console.log(freezedObj);
Output
{ name: 'KRUNAL', education: 'BE IT' }
You can check whether an object is frozen using Object.isFrozen().
console.log(Object.isFrozen(freezedObj));
Output
true
Example 2: Using strict mode
When we write the above code in strict mode, it will give an exception.
'use strict';
let student = { name: 'KRUNAL', education: 'BE IT' };
let freezedObj = Object.freeze(student);
freezedObj.name = 'ANKIT';
console.log(freezedObj);
Output
TypeError: Cannot assign to read only property 'name' of object '#<Object>'
at Object.<anonymous> (/Users/ankitlathiya/Desktop/code/app.js:4:17)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47
Browser Compatibility
- Chrome 6 and above
- Edge 12 and above
- Firefox 4 and above
- Opera 12 and above
- Safari 5.1 and above