ghasemkiani avatar

JavaScript Basics: Object.freeze and Object.isFrozen

ghasemkiani

Published: 10 Feb 2018 › Updated: 10 Feb 2018JavaScript Basics: Object.freeze and Object.isFrozen

JavaScript Basics: Object.freeze and Object.isFrozen

In the previous posts, I discussed about two levels of object protection: Object.preventExtensions and Object.seal. The last level of protection is Object.freeze, which also makes all the properties unchangeable. You cannot add a new property, you cannot delete an existing property, you cannot reconfigure it, and you cannot change its value.

The following code snippet demonstrates the effects of Object.freeze:

    let myObj = {
        name: "Ali",
    };
    Object.freeze(myObj);
    
    console.log(Object.isFrozen(myObj)); // true

    // You cannot add new properties. This fails silently.
    myObj.age = 19;
    console.log(myObj.age); // undefined

    // You cannot reconfigure existing properties.
    try {
        Object.defineProperty(myObj, "name", {
            get() {
                return "Susan";
            },
        });
        console.log(myObj.name);
    } catch (e) {
        console.log(e); // TypeError: Cannot redefine property: name
    }

    // You cannot change property values.
    myObj.name = "Susan";
    console.log(myObj.name); // Ali
    try {
        Object.defineProperty(myObj, "name", {
            value: "Aria",
        });
        console.log(myObj.name); // Ali
    } catch(e) {
        console.log(e); // TypeError: Cannot redefine property: name
    }

    // You can add new properties to the prototype.
    myObj.__proto__.age = 14;
    console.log(myObj.age); // 14

    // You cannot change the prototype.
    try {
        Object.setPrototypeOf(myObj, {
            grade: 9,
        });
        console.log(myObj.grade);
    } catch (e) {
        console.log(e); // TypeError: # is not extensible
    }
    try {
        myObj.__proto__ = {
            grade: 9,
        };
        console.log(myObj.grade);
    } catch (e) {
        console.log(e); // TypeError: # is not extensible
    }

In short, Object.freeze prevents extensions to the object and makes all the existing properties non-configurable, and also prevents the values of the existing properties from being changed. In this way, the object becomes immutable.


Related Posts

Leave JavaScript Basics: Object.freeze and Object.isFrozen to:

Written by

Read more #javascript posts


Best Posts From ghasemkiani

We have not curated any of ghasemkiani's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ghasemkiani