Constraining JavaScript Objects


JavaScript has a number of methods that can be called to limit (or restrict) future modifications to an object after it has been created. These functions do similar things but have some important differences.

seal() prevents you from adding new properties or removing existing ones from an object. You may still change property values. freeze() prevents you from adding new properties, removing existing properties or changing the value of a property in an object. preventExtensions() will prevent new properties from being added to an object. It still allows properties to be removed, or values to be changed. The main differences is seal() will lock down an object’s property structure, but still allow values to be change, freeze() also removes the ability to alter values as well. If you need to remove properties but remove the ability to add new ones preventExtensions() is what you would use.

//seal()

var person = {
        name : 'Joe',
        age: 30
    }

Object.seal(person);

if( Object.isSealed(person) ){

    person.name = 'John';
    person.country = 'USA';
    delete person.age;

    console.log(person); //logs {name:'John', age: 30}

}

//freeze()

var person = {
        name : 'Jane',
        age: 22
    }

Object.freeze(person);

if( Object.isFrozen(person) ){

    person.name = 'Laura';
    person.country = 'New Zealand';
    delete person.age;

    console.log(person); //logs {name:'Jane', age: 22}

}

//preventExtensions()

var person = {
        name : 'Stephen',
        age: 42
    }

Object.preventExtensions(person);

if( !Object.isExtensible(person) ){

    person.name = 'Trevor';
    person.country = 'Canada';
    delete person.age;

    console.log(person); //logs {name:'Trevor'}

}

Other Resources