JS Coding Questions Logo
JS Coding Questions
#263💼 Interview💻 Code

How do you prevent an object from being extend

Advertisement

728x90

The Object.preventExtensions() method is used to prevent new properties from ever being added to an object. In other words, it prevents future extensions to the object. Let's see the usage of this property,

javascript
1const newObject = {};
2
3Object.preventExtensions(newObject); // NOT extendable
4
5try {
6  Object.defineProperty(newObject, "newProperty", {
7  // Adding new property
8  value: 100,
9  });
10} catch (e) {
11  console.log(e); // TypeError: Cannot define property newProperty, object is not extensible
12}

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 6

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
263of476