Skip to content

JavaScript Object freeze | Method

  • by

The JavaScript object freeze method is used to make an object immutable, i.e. you cannot change its properties. It accepts an object and returns the same object. Now the object cannot have any of its properties removed or any new properties added.

Object.freeze(obj);

JavaScript Object freeze example

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
   const obj = {
    prop: 100
  };

  Object.freeze(obj);

  obj.prop = 200;

  console.log(obj.prop);
  console.log(obj)

</script>
</body>
</html>

Output:

JavaScript Object freeze

Can’t mutate a frozen object

object1 = {
  prop1: 1,
  prop2: 2
}

object2 = Object.freeze(object1);

console.log(object1 === object2); // both objects are refer to the same instance

object2.prop3 = 3; // no new property can be added, won't work

delete object2.prop1; // no property can be deleted, won't work

console.log(object2); // object unchanged

Objects with references aren’t fully frozen

const object = {
  prop1: 1,
  nestedObj: {
    nestedProp1: 1,
    nestedProp2: 2,
  } 
}


const frozen = Object.freeze(object);

frozen.prop1 = 5; // won't have any effect
frozen.nestedObj.nestedProp1 = 5; //will update because the nestedObject isn't frozen

console.log(frozen);

It’s important to note that Object.freeze() works at the top level of the object. If the object has nested objects, the nested objects are not automatically frozen. You would need to recursively call Object.freeze() on each nested object if you want them to be frozen as well.

const nestedObject = {
  nestedProp: 'nestedValue'
};

const myObject = {
  prop1: 'value1',
  prop2: nestedObject
};

Object.freeze(myObject);
Object.freeze(myObject.prop2);

// Now both myObject and its nested object are frozen

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *