The Object.seal() method prevents the addition or deletion of properties.
It also makes existing properties non-configurable.
You can use the Object.isSealed() method to check if an object is sealed.
Note: The Object.seal() method will fail silently in non-strict mode but will throw a TypeError in strict mode. |
“use strict” // Create Object const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; // Seal Object Object.seal(person) // This will throw an error delete person.age; |
Since arrays are objects, they can also be sealed.
// Create Array const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; Object.seal(fruits); // This will throw an error: fruits.push(“Kiwi”); |
The Object.isSealed() method checks if an object is sealed.
It returns true if the object is sealed.
// Create Object const person = {firstName:“John”, lastName:“Doe”}; // Seal Object Object.seal(person); // This will return true let answer = Object.isSealed(person); |
// Create Array const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; // Seal Array Object.seal(fruits); // This will return true let answer = Object.isSealed(fruits); |
The Object.freeze() method prevents any changes to an object.
Frozen objects become read-only, disallowing modifications, additions, or deletions of properties.
Note: The Object.freeze() method will fail silently in non-strict mode but will throw a TypeError in strict mode. |
“use strict” // Create Object const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; // Freeze Object Object.freeze(person) // This will throw an error person.age = 51; |
Since arrays are objects, they can also be frozen.
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; Object.freeze(fruits); // This will trow an error: fruits.push(“Kiwi”); |
The Object.isFrozen() method checks if an object is frozen.
It returns true if the object is frozen.
// Create Object const person = {firstName:“John”, lastName:“Doe”}; // Freeze Object Object.freeze(person); // This will return true let answer = Object.isFrozen(person); |
// Create Array const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; Object.freeze(fruits); // This will return true: let answer = Object.isFrozen(fruits); |