// Prevents re-assignment const car = {type:“Fiat”, model:“500”, color:“white”}; // Prevents adding object properties Object.preventExtensions(object) // Returns true if properties can be added to an object Object.isExtensible(object) // Prevents adding and deleting object properties Object.seal(object) // Returns true if object is sealed Object.isSealed(object) // Prevents any changes to an object Object.freeze(object) // Returns true if object is frozen Object.isFrozen(object) |
Since arrays are objects, they can also be prevented from being extended.
// Create Array const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; Object.preventExtensions(fruits); // This will throw an error: fruits.push(“Kiwi”); |
You can use Object.isExtensible() to determine if an object is extensible.
The Object.isExtensible() method returns true if the object is extensible.
// Create Object const person = {firstName:“John”, lastName:“Doe”}; // Prevent Extensions Object.preventExtensions(person); // This will return false let answer = Object.isExtensible(person); |
// Create Array const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; // Prevent Extensions Object.preventExtensions(fruits); // This will return false let answer = Object.isExtensible(fruits); |