0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Object.freeze in JavaScript: Syntax and Examples

Use Object.freeze(object) to make an object immutable, preventing any changes to its properties. Once frozen, you cannot add, delete, or modify properties of that object.
📐

Syntax

The Object.freeze() method takes one argument: the object you want to freeze. It returns the same object but in a frozen state.

  • object: The object to freeze.
  • Returns the frozen object.
javascript
const frozenObject = Object.freeze(object);
💻

Example

This example shows how freezing an object prevents changes to its properties.

javascript
const user = {
  name: 'Alice',
  age: 25
};

Object.freeze(user);

user.age = 30; // This will not change the age
user.city = 'New York'; // This will not add a new property

console.log(user);
Output
{"name":"Alice","age":25}
⚠️

Common Pitfalls

1. Object.freeze is shallow: It only freezes the top-level properties. Nested objects inside remain mutable.

2. No errors thrown: Trying to change a frozen object silently fails in non-strict mode.

3. Use strict mode to catch errors: In strict mode, attempts to modify a frozen object throw a TypeError.

javascript
'use strict';
const person = {
  name: 'Bob',
  address: {
    city: 'Paris'
  }
};

Object.freeze(person);

// This changes nested object property because freeze is shallow
person.address.city = 'London';

console.log(person.address.city); // Outputs 'London'

// In strict mode, this throws an error
person.name = 'Robert'; // TypeError: Cannot assign to read only property 'name'
Output
London
📊

Quick Reference

FeatureDescription
Object.freeze(object)Makes the object immutable (shallow freeze)
Cannot add propertiesNew properties cannot be added after freezing
Cannot delete propertiesExisting properties cannot be removed
Cannot modify propertiesValues of existing properties cannot be changed
Shallow freezeNested objects remain mutable unless frozen separately
Strict modeThrows error on modification attempts

Key Takeaways

Object.freeze makes an object immutable by preventing changes to its properties.
Freezing is shallow; nested objects inside remain changeable unless frozen separately.
In non-strict mode, changes fail silently; use strict mode to catch errors.
You cannot add, delete, or modify properties of a frozen object.
Use Object.freeze to protect objects from accidental changes in your code.