JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)
What is the purpose of the freeze method
Below are the main benefits of using freeze method,
- It is used for freezing objects and arrays.
- It is used to make an object immutable.
Practical Code Example
javascript
// Object.freeze(): Makes an object completely immutable
const config = { apiEndpoint: 'https://api.v1.com' };
Object.freeze(config);
config.apiEndpoint = 'https://hacked.com'; // Fails silently (or throws TypeError in strict mode)
config.newProp = 'fail'; // Cannot add new properties
delete config.apiEndpoint; // Cannot delete properties
console.log(config.apiEndpoint); // 'https://api.v1.com'