Abhay Jain

Jan 13, 2021

4 min read

Object.freeze vs Object.seal

Object.freeze()

  • You can’t add new properties to the object
  • You can’t modify the properties if they are not objects or arrays themselves. (More on this later)
  • You can’t delete properties from the object
let objectToFreeze = {
age: 28,
name: "Damien",
pets: ["Symba", "Hades", "Kiwi"],
sibling: {
age: 25,
name: "Corentin",
},
};

Object.freeze(objectToFreeze);

delete objectToFreeze.age;
objectToFreeze.name = "Ben";
objectToFreeze.pets.push("Grenade");
objectToFreeze.sibling.age = 26;
objectToFreeze.lastName = "Cosset";
console.log(objectToFreeze)

// objectToFreeze :
{ age: 28,
name: 'Damien',
pets: [ 'Symba', 'Hades', 'Kiwi', 'Grenade' ],
sibling: {
age: 26,
name: 'Corentin'
}
}

Shallow freeze

let allYouCanFreeze = (obj) => {
// Retrieve the properties names
let propNames = Object.getOwnPropertyNames(obj);

// Loop through the properties
// If typeof is "object", meaning an array or object, use recursion to freeze its contents.
for (let name of propNames) {
let value = obj[name];
obj[name] =
value && typeof value === "object" ? allYouCanFreeze(value) : value;
}

// Finally, freeze the main object
return Object.freeze(obj);
};
let objectToFreeze = {
age: 28,
name: "Damien",
pets: ["Symba", "Hades", "Kiwi"],
sibling: {
age: 25,
name: "Corentin",
},
};

allYouCanFreeze(objectToFreeze);

// Now we can't touch the pets array and the sibling object

objectToFreeze.age = 26; // Now, fails.
objectToFreeze.pets.push("Grenade"); // Now, fails

Object.isFrozen

Object.isFrozen(objectToFreeze); // === truelet unfrozenObj = { a: 42 };
Object.isFrozen(unfrozenObj); // === false

Object.seal

  • You can’t remove or add elements to the object.
  • You can modify existing properties.
let objectToSeal = {
name: "Damien",
age: 28,
pets: ["Symba", "Hades", "Kiwi"],
sibling: {
age: 25,
name: "Corentin",
},
};
Object.seal(objectToSeal);
delete objectToSeal.name;
objectToSeal.age = 56;
objectToSeal.lastName = "Cosset";
objectToSeal.sibling.age = 45;
objectToSeal.pets.push("Grenade");
//objectToSeal new contents{
name: 'Damien',
age: 56, //modifying worked
pets: ['Symba', 'Hades', 'Kiwi', 'Grenade'], // push worked
sibling: {
age: 45, // Modifying worked
name: 'Corentin'
}
}
// adding and deleting failed!

Object.isSealed

Object.isSealed(objectToSeal); // === truelet notSealedObj = { a: 54 };
Object.isSealed(notSealedObj); // === false

What about const?

What about prototypes?

let freezeThat = {
name: 'Damien'
}
let sealThis = {
age 28
}
Object.freeze(freezeThat)
Object.seal(sealThis)
// These two lines will fail!
Object.setPrototypeOf(freezeThat, {x: 26})
Object.setPrototypeOf(sealThis, {alive: true})