The Object freeze() method

By

Learn how the JavaScript Object.freeze() method makes an object immutable, so no properties can be added, removed, or changed, and returns that same object.

~~~

The JavaScript Object.freeze() method makes an object immutable. No properties can be added, no properties can be removed, and existing properties cannot be changed.

It mutates the object you pass and returns that same object:

'use strict'

const dog = {
  breed: 'Siberian Husky'
}

const myDog = Object.freeze(dog)

Object.isFrozen(dog) //true
dog === myDog //true

dog.name = 'Roger' //TypeError
dog.breed = 'Labrador' //TypeError
delete dog.breed //TypeError

Also see Object.isFrozen()

Both dog and myDog point to the same frozen object. There is no way to unfreeze it.

Why would you want this? Freezing is useful for values that must never change, like a configuration object or a set of constants. const only prevents reassigning the variable. It does nothing to protect the object it points to. Freezing covers that second part:

const config = Object.freeze({
  apiUrl: 'https://api.flaviocopes.com',
  retries: 3
})

config.retries = 5 //fails

What happens without strict mode?

In strict mode, writing to a frozen object throws a TypeError. Without it, the write fails silently: no error, and the object stays unchanged.

The silent failure is the pitfall. You assign a property, nothing complains, and later the value is not there. If a mutation seems to disappear, check the object with Object.isFrozen(). ES modules and class bodies run in strict mode automatically, so modern code usually gets the error.

Freezing is shallow

Object.freeze() only freezes the object itself. Objects stored in its properties stay mutable:

const user = Object.freeze({
  name: 'Flavio',
  address: {
    city: 'Milan'
  }
})

user.address.city = 'Rome' //works
user.address.city //'Rome'

Freeze the nested objects too when you need the whole structure locked.

How does it compare to preventExtensions() and seal()?

Calling Object.freeze() is the equivalent of calling Object.preventExtensions() to prevent adding new properties, plus setting all existing properties as non-configurable and all data properties as non-writable.

Object.seal() sits in the middle. It prevents adding and removing properties, but you can still change the values of existing ones.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: