Object Protection in JavaScript
Object Protection in JavaScript
What is Object Protection?
Object protection refers to techniques that restrict or control how an object’s properties can be modified, added, or deleted to preserve integrity and prevent unwanted changes.
Ways to Protect Objects in JavaScript
1. Object.freeze()
Makes an object immutable:
You cannot add, delete, or modify existing properties.
Shallow freeze only (nested objects are not frozen).
const person = { name: "Alice", age: 30};Object.freeze(person);person.age = 31; // Ignored in strict mode, fails silently otherwiseperson.city = "NY"; // Cannot add new propertiesdelete person.name; // Cannot delete propertiesconsole.log(person); // { name: "Alice", age: 30 }2. Object.seal()
Prevents adding or deleting properties.
Allows modification of existing properties.
const person = { name: "Alice", age: 30};Object.seal(person);person.age = 31; // Allowedperson.city = "NY"; // Not alloweddelete person.name; // Not allowedconsole.log(person); // { name: "Alice", age: 31 }3. Object.preventExtensions()
Prevents adding new properties only.
Existing properties can be modified or deleted.
const person = { name: "Alice", age: 30};Object.preventExtensions(person);person.city = "NY"; // Not allowedperson.age = 31; // Alloweddelete person.name; // Allowedconsole.log(person); // { age: 31 }Checking Protection Status
console.log(Object.isFrozen(person)); // true or falseconsole.log(Object.isSealed(person)); // true or falseconsole.log(Object.isExtensible(person)); // true or falseSummary
| Method | Can Add Properties | Can Delete Properties | Can Modify Properties |
|---|---|---|---|
Object.freeze() | No | No | No |
Object.seal() | No | No | Yes |
Object.preventExtensions() | No | Yes | Yes |
Would you like to see examples with nested objects or Proxy-based protection?