JavaScript Basics: Object.preventExtensions and Object.isExtensible

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@ghasemkiani·
0.000 HBD
JavaScript Basics: Object.preventExtensions and Object.isExtensible
In JavaScript, an object is extensible by default. This means that new properties can be added to the object. In some circumstances, you my want to prevent extensions to the object. To this end, you can use `Object.preventExtensions`. This function prevents any extensions to the object, so that no new property can be added to the object. If you try to add new properties to the object, it will cause a `TypeError` (or fail silently if not in strict mode).

Here is an example:

```
	let myObj = {
		name: "Ali",
	};
	Object.isExtensible(myObj); // true
	Object.preventExtensions(myObj);
	Object.isExtensible(myObj); // false
	myObj.age = 19; // fails silently
	myObj.age; // undefined
```

It should be noted that after making an object inextensible, its `__proto__` property becomes immutable. In other words, you cannot assign a new value to the `__proto__` property. However, if the prototype is extensible, you can add new properties to the prototype.

As the EcmaScript standard attempts to organize the global objects, this functions are also available on the `Reflect` global object. So you can use `Reflect.isExtensible` and `Reflect.preventExtensions` instead.

---

## Related Posts

* [JavaScript Basics: Object.create](https://steemit.com/javascript/@ghasemkiani/javascript-basics-01)
* [JavaScript Basics: Object.assign](https://steemit.com/javascript/@ghasemkiani/javascript-basics-02)
* [JavaScript Basics: Object.getPrototypeOf and Object.setPrototypeOf](https://steemit.com/javascript/@ghasemkiani/javascript-basics-03)
* [JavaScript Basics: Object.keys, Object.values, and Object.entries](https://steemit.com/javascript/@ghasemkiani/javascript-basics-04)
* [JavaScript Basics: Object.is](https://steemit.com/javascript/@ghasemkiani/javascript-basics-05)
* [JavaScript Basics: Object.prototype.hasOwnProperty](https://steemit.com/javascript/@ghasemkiani/javascript-basics-06)
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , ,