Object.freeze()

Freezes an object, blocking the addition, removal, and change of its properties.

Returns
The same object, now frozen.
Changes the original
Yes
On this page

Example

#
JavaScript
const LEVELS = Object.freeze({ easy: 1, medium: 2, hard: 3 })

try {
  LEVELS.easy = 5
} catch (error) {
  console.log(error.name)
}
console.log(LEVELS.easy)
console.log(Object.isFrozen(LEVELS))
Console
TypeError
1
true

Definition and usage

#

The Object.freeze() method makes an object impossible to change further: you can’t add new properties, remove existing ones, or change their values. In strict mode, which is how modules run, any such attempt throws a TypeError.

It’s useful for configuration constants and lookup tables that shouldn’t be accidentally changed somewhere else in the program.

Freezing is shallow: nested objects can still be changed, unless you freeze them separately. Object.isFrozen() checks whether an object is frozen.

Syntax

#
Syntax
Object.freeze(obj)

Parameters

#
  • obj

    object

    The object to freeze.

More examples

#
Freezing is shallow
JavaScript
const config = Object.freeze({ api: { timeout: 1000 } })
config.api.timeout = 5000
console.log(config.api.timeout)
Console
5000

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • const only protects the variable assignment. You need Object.freeze() to lock down the object’s contents.
  • For a deep freeze, you have to walk recursively through the nested objects.

Related entries

#

Spotted a mistake or missing an example? Write to us.