Middle
How can you prevent modification of an object in JavaScript?
sobes.tech AI
Answer from AI
You can use the built-in Object methods:
Object.preventExtensions(obj): Prevents adding new properties to an object but allows modifying and deleting existing ones.Object.seal(obj): Prevents adding and deleting properties but allows modifying existing properties. Essentially, this ispreventExtensions+ delete prohibition.Object.freeze(obj): Prevents adding, deleting, and modifying properties. Makes the object shallowly immutable. This isseal+ prohibition of changing existing properties.
Example of usage:
// Original object
let myObject = { name: 'Alice', age: 30 };
// preventExtensions
Object.preventExtensions(myObject);
myObject.city = 'London'; // Will not work in strict mode, will be ignored in non-strict mode.
// seal
let mySealedObject = { name: 'Bob', age: 25 };
Object.seal(mySealedObject);
mySealedObject.age = 26; // Will work
delete mySealedObject.name; // Will not work in strict mode.
mySealedObject.city = 'Paris'; // Will not work in strict mode.
// freeze
let myFrozenObject = { name: 'Charlie', age: 35 };
Object.freeze(myFrozenObject);
myFrozenObject.age = 36; // Will not work in strict mode.
delete myFrozenObject.name; // Will not work in strict mode.
myFrozenObject.city = 'New York'; // Will not work in strict mode.
Note that Object.freeze is shallow. If the object contains references to other objects, those nested objects can be modified unless they are also frozen. For deep freezing, a recursive function is needed.
// Example of deep freezing
function deepFreeze(obj) {
Object.freeze(obj); // Freeze the current object
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const prop = obj[key];
// If the property is an object (and not null), recursively freeze it
if (typeof prop === 'object' && prop !== null && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
}
}
}
let nestedObject = {
name: 'Deep',
details: {
level: 1
}
};
deepFreeze(nestedObject);
nestedObject.details.level = 2; // Will not work in strict mode.
Comparison table:
| Method | Adding properties | Deleting properties | Modifying properties |
|---|---|---|---|
Object.preventExtensions() |
No | Yes | Yes |
Object.seal() |
No | No | Yes |
Object.freeze() |
No | No | No |