Prevent Object from adding new Properties in JavaScript

Learn how to use preventExtensions to stop adding new properties to a JavaScript Object

Photo by Dan-Cristian Pădureț on Unsplash

The Object.preventExtensions() method prevents new properties from added to an object.

In the above code, after calling preventExtensions on the user object, when we try to add age property JavaScript will thow TypeError .

  • preventExtensions method returns the object being made non-extensible.
  • There is no way to make an object extensible again once it has been made non-extensible.
  • To check if the object is non-extensible we can use Object.isExtensible()
  • preventExtensions()method only prevents addition of own properties. Properties can still be added to the object prototype.

preventExtensions() makes the [[prototype]] of the user object immutable, any [[prototype]] re-assignment(adding new property) will throw a TypeError. This behavior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable.

In other word when we try to change the __proto__ prototype of the non-extensible object , JavaScript will throw error

  • You can delete the property of the non-extensible object

You can also prevented from adding properties by using defineProperty

A non-object argument to preventExtensions will be treated as if it was a non-extensible ordinary object, return it.

Object.preventExtensions(1); // returns 1

Articles related to JavaScript.