Skip to main content

object.freeze in javascript

Object.freeze() in JavaScript is a static method that freezes an object, making it immutable. This means that once an object is frozen:
  • New properties cannot be added. 
    Attempts to add new properties will fail silently in non-strict mode and throw a TypeError in strict mode.
  • Existing properties cannot be removed. 
    Deleting properties will also fail silently or throw an error in strict mode. 
Existing properties cannot be modified. 
The values of existing properties cannot be changed, and their attributes (enumerability, configurability, writability) cannot be altered.
The object's prototype cannot be re-assigned.

How to use Object.freeze():
You simply pass the object you want to freeze as an argument to the method. It returns the same object, not a frozen copy. 
JavaScript
const myObject = {
  name: 'Alice',
  age: 30,
  address: {
    city: 'New York',
    zip: '10001'
  }
};

Object.freeze(myObject);

// Attempts to modify the frozen object:
myObject.age = 31; // Fails silently (or throws TypeError in strict mode)
myObject.newProperty = 'value'; // Fails silently (or throws TypeError in strict mode)
delete myObject.name; // Fails silently (or throws TypeError in strict mode)

console.log(myObject); // { name: 'Alice', age: 30, address: { city: 'New York', zip: '10001' } }
Important Considerations:
Shallow Freeze: 
Object.freeze() performs a shallow freeze. This means it only freezes the immediate properties of the object. If an object contains other objects or arrays as properties, those nested objects/arrays are not frozen and can still be modified. To achieve a "deep freeze," you would need to recursively freeze all nested objects.
Immutability: 
Object.freeze() is a powerful tool for enforcing immutability, which can be beneficial for data integrity, preventing unintended side effects, and creating constant-like objects.
Strict Mode: 
In strict mode, attempts to modify a frozen object will throw a TypeError, which can help in identifying and debugging code that inadvertently tries to alter frozen objects.