Object.freeze()

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed.  The method returns the object in a frozen state.

Syntax

Object.freeze(obj)

Parameters

obj
The object to freeze.

Return value

The frozen object.

Description

Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a TypeError exception (most commonly, but not exclusively, when in strict mode).

Values cannot be changed for data properties. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen whereafter its elements cannot be altered. No elements can be added or removed from it as well.

Examples

var obj = {
  prop: function() {},
  foo: 'bar'
};
// New properties may be added, existing properties may be
// changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
// Both the object being passed as well as the returned
// object will be frozen. It is unnecessary to save the
// returned object in order to freeze the original.
var o = Object.freeze(obj);
o === obj; // true
Object.isFrozen(obj); // === true
// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';
// In strict mode such attempts will throw TypeErrors
function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws a TypeError
  delete obj.quaxxor; // throws a TypeError
  obj.sparky = 'arf'; // throws a TypeError
}
fail();
// Attempted changes through Object.defineProperty; 
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });
// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }
// A frozen array is like a tuple.
let a=[0];
Object.freeze(a);
// The array cannot be modified now.
a[0]=1;
a.push(2);
// a=[0]
// A frozen array can be unpacked normally.
let b, c;
[b,c]=Object.freeze([1,2]);
// b=1, c=2

The object being frozen is immutable.  However, it is not necessarily constant. The following example shows that a frozen object is not constant (freeze is shallow).

obj1 = {
  internal: {}
};
Object.freeze(obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'

To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects.  The object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed.  Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects. 

To make an object constant, recursively freeze each property which is of type object (deep freeze).  Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered.   An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can supress calling deepFreeze() recursively when an object is in the process of being made constant.  You still run a risk of freezing an object that shouldn't be frozen, such as [window].

// To do so, we use this function.
function deepFreeze(obj) {
  // Retrieve the property names defined on obj
  var propNames = Object.getOwnPropertyNames(obj);
  // Freeze properties before freezing self
  propNames.forEach(function(name) {
    var prop = obj[name];
    // Freeze prop if it is an object
    if (typeof prop == 'object' && prop !== null)
      deepFreeze(prop);
  });
  // Freeze self (no-op if already frozen)
  return Object.freeze(obj);
}
obj2 = {
  internal: {}
};
deepFreeze(obj2);
obj2.internal.a = 'anotherValue';
obj2.internal.a; // undefined

Notes

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned.

> Object.freeze(1)
TypeError: 1 is not an object // ES5 code
> Object.freeze(1)
1                             // ES2015 code

Comparison to Object.seal()

Objects sealed with Object.seal() can have their existing properties changed. Existing properties in objects frozen with Object.freeze() are made immutable.

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Object.freeze' in that specification.
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.freeze' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'Object.freeze' in that specification.
Living Standard  

Browser compatibility

Feature Firefox (Gecko) Chrome Edge Internet Explorer Opera Safari
Basic support 4.0 (2) 6 (Yes) 9 12 5.1
Feature Firefox Mobile (Gecko) Android Edge IE Mobile Opera Mobile Safari Mobile
Basic support ? ? (Yes) ? ? ?

See also