Prevent Object from adding new Properties in JavaScript

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

Image for post
Image for post
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.
  • 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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store