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

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center