-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, objects are dynamic and mutable by default, meaning their properties can be added, modified, or deleted at any time. While this flexibility is useful, it can also lead to unintended modifications, bugs, or security issues, especially in large applications or shared codebases.
To maintain data integrity and prevent accidental changes, JavaScript provides several mechanisms for object protection. These mechanisms allow developers to control, lock, or freeze objects while still using them effectively in applications. Understanding object protection is essential for robust and maintainable code.
Object.preventExtensions()
The simplest form of object protection is to prevent new properties from being added:
const person = {
name: "Alice",
age: 25
};
Object.preventExtensions(person);
person.gender = "Female"; // Ignored in strict mode, silently fails otherwise
console.log(person.gender); // undefined
person.age = 30; // Allowed
console.log(person.age); // 30
Object.preventExtensions()
does not prevent modification or deletion of existing properties.
Use Object.isExtensible(obj)
to check if an object is extensible:
console.log(Object.isExtensible(person)); // false
Useful when you want to lock down the object structure but still allow property updates.
Object.seal()
A sealed object prevents adding or deleting properties, but still allows modification of existing properties:
const student = {
name: "John",
age: 20
};
Object.seal(student);
student.gender = "Male"; // Ignored
delete student.age; // Fails
student.name = "Alice"; // Allowed
console.log(student); // { name: "Alice", age: 20 }
Object.isSealed(obj)
checks if an object is sealed:
console.log(Object.isSealed(student)); // true
Sealing is useful when you want to fix the shape of an object but still allow value updates.
Object.freeze()
A frozen object is completely immutable:
const car = {
brand: "Toyota",
model: "Camry"
};
Object.freeze(car);
car.brand = "Honda"; // Ignored
car.year = 2025; // Ignored
delete car.model; // Fails
console.log(car); // { brand: "Toyota", model: "Camry" }
Object.isFrozen(obj)
checks if an object is frozen:
console.log(Object.isFrozen(car)); // true
Freezing is ideal for constants or configuration objects that should never change during runtime.
Note: Freezing is shallow, meaning nested objects are not frozen. To fully freeze a nested structure, a deep freeze function is required.
const company = {
name: "TechCorp",
address: { city: "NYC", zip: 10001 }
};
Object.freeze(company);
company.address.city = "LA"; // Allowed, because nested object is not frozen
Object.defineProperty()
for Controlled AccessAnother way to protect objects is to define non-writable, non-configurable, or non-enumerable properties:
const employee = {};
Object.defineProperty(employee, "salary", {
value: 50000,
writable: false,
configurable: false,
enumerable: true
});
employee.salary = 60000; // Ignored
console.log(employee.salary); // 50000
writable: false
prevents changes to the property value.
configurable: false
prevents deletion or reconfiguration.
enumerable: false
hides the property in loops like for...in
.
This method allows fine-grained control over specific properties rather than the entire object.
Since Object.freeze()
, seal()
, and preventExtensions()
are shallow, protecting nested objects requires recursion:
function deepFreeze(obj) {
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach(prop => {
if (typeof obj[prop] === "object" && obj[prop] !== null) {
deepFreeze(obj[prop]);
}
});
}
const data = {
user: { name: "Alice", age: 25 },
settings: { theme: "dark" }
};
deepFreeze(data);
data.user.name = "Bob"; // Ignored
console.log(data.user.name); // Alice
Deep freezing ensures complete immutability, preventing accidental changes to nested structures.
Use preventExtensions()
to stop adding new properties.
Use seal()
to fix the object structure but allow updates.
Use freeze()
for full immutability of shallow objects.
Use deep freeze for nested object protection.
Use defineProperty()
for property-level control.
Be aware of performance trade-offs: freezing large objects or deep structures may impact performance.
Protecting objects is important in shared libraries, API responses, or global configurations.
JavaScript objects are mutable by default, which can lead to unintended modifications.
Object protection methods help maintain data integrity:
Object.preventExtensions()
: Prevent new properties.
Object.seal()
: Prevent adding or deleting properties.
Object.freeze()
: Fully immutable object (shallow).
Object.defineProperty()
: Fine-grained property control.
Deep freeze: Recursively protect nested objects.
Object protection is essential for robust, predictable, and maintainable code.
These features are widely used in real-world applications, frameworks, and libraries to enforce consistency and prevent accidental changes.
Mastering object protection allows developers to write safer and more reliable JavaScript code, which is critical in professional development environments.
Preventing Extensions
Create an object person
with properties name
and age
. Use Object.preventExtensions()
and try adding a new property gender
. Log the result.
Sealing an Object
Create an object student
with properties name
and grade
. Seal the object using Object.seal()
. Try adding, deleting, and updating properties and log the object.
Freezing an Object
Create an object car
with brand
and model
. Freeze it using Object.freeze()
and try modifying existing properties or adding new ones. Log the final object.
Checking Extensibility, Sealed, and Frozen Status
Use Object.isExtensible()
, Object.isSealed()
, and Object.isFrozen()
on various objects to verify their protection status.
Non-Writable Property
Create an object employee
and define a salary
property using Object.defineProperty()
with writable: false
. Attempt to change the salary and log the value.
Non-Configurable Property
Create a property on an object with configurable: false
and attempt to delete or redefine it. Log the results.
Non-Enumerable Property
Define a property secret
on an object with enumerable: false
. Loop over the object properties using for...in
and log the output to show it is hidden.
Deep Freeze
Create a nested object data
with user details and settings. Implement a deep freeze function and try modifying a nested property. Log the result.
Combination of Seal and DefineProperty
Create an object, seal it, and define a non-writable property. Attempt to add, delete, and modify properties and log all changes.
Protecting Configuration Object
Create a configuration object for an application and freeze it completely. Try changing top-level and nested properties to demonstrate immutability.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts