JavaScript Object.freeze()

Definition and usage

Object.freeze() The method is used to prevent any changes to the object.

In non-strict mode,Object.freeze() The method will fail silently.

In strict mode,Object.freeze() The method will throw a TypeError.

Frozen objects are read-only. Modifications, additions, or deletions of properties are not allowed.

Can be used Object.isFrozen() Methods to check if an object is frozen.

Related methods:

Object.preventExtensions() Modification is allowed, but adding properties is prevented.

Object.seal() Allows modification, but prevents addition and deletion of properties.

Object.freeze() Prevents modification, addition, and deletion of properties.

Object.isExtensible() Returns true if the object is extensible.

Object.isSealed() Returns true if the object is sealed.

Object.isFrozen() Returns true if the object is frozen.

Instance

Example 1

"use strict"
// Create an object
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50,
  eyeColor: "blue"
};
// Freeze the object
Object.freeze(person);
// This will throw an error
person.age = 51;

Try It Yourself

Example 2

const fruits = ["Banana", "Orange", "Apple", "Mango"];
Object.freeze(fruits);
// This will throw an error:
fruits.push("Kiwi");

Try It Yourself

Syntax

Object.freeze(object)

Parameter

Parameter Description
object Required. The object to be frozen.

Return Value

Type Description
Object Frozen objects.

Browser Support

Object.freeze() Is a feature of ECMAScript5 (ES5).

Since July 2013, all modern browsers have fully supported ES5 (JavaScript 2009):

Chrome Edge Firefox Safari Opera
Chrome 23 IE/Edge 11 Firefox 21 Safari 6 Opera 15
September 2012 September 2012 April 2013 July 2012 July 2013