-
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, protecting objects is essential when you want to prevent accidental changes, maintain data integrity, or enforce immutability in applications. Object protection techniques allow developers to control how objects are accessed and modified, making code more reliable and less error-prone. Understanding object protection is crucial for creating secure, maintainable, and scalable JavaScript applications.
In this tutorial, you will learn about different ways to protect objects, including freezing, sealing, and preventing extensions. You will also see practical examples, common mistakes, best practices, and real-world applications.
Object protection is important because it allows you to:
Prevent accidental modification of object properties
Maintain consistency and reliability of critical data
Control what properties can be added, changed, or deleted
Avoid bugs caused by unintended changes in shared objects
Implement immutability in functional programming or large-scale applications
Without proper object protection, objects can be modified unintentionally, leading to unexpected behavior, data corruption, and difficult-to-maintain code.
JavaScript provides several built-in methods to protect objects:
Object.freeze()
Object.seal()
Object.preventExtensions()
Each method provides a different level of protection.
Object.freeze() makes an object immutable. After freezing, you cannot add, delete, or modify properties.
const student = {
name: "Aarushi",
age: 20
};
Object.freeze(student);
student.age = 21; // Ignored in strict mode
student.course = "JS"; // Ignored
delete student.name; // Ignored
console.log(student);
Output:
{ name: 'Aarushi', age: 20 }
Frozen objects are particularly useful when you want to ensure that a configuration object or constant data cannot be changed during runtime.
Object.seal() prevents adding or deleting properties but allows modification of existing properties.
const student = {
name: "Priya",
age: 22
};
Object.seal(student);
student.age = 23; // Allowed
student.course = "React"; // Not allowed
delete student.name; // Not allowed
console.log(student);
Output:
{ name: 'Priya', age: 23 }
Sealed objects are useful when you want to allow updates to existing data but prevent structural changes.
Object.preventExtensions() only prevents adding new properties. Existing properties can still be modified or deleted.
const student = {
name: "Saanvi",
age: 21
};
Object.preventExtensions(student);
student.age = 22; // Allowed
student.course = "Node.js"; // Not allowed
delete student.name; // Allowed
console.log(student);
Output:
{ name: 'Saanvi', age: 22 }
This method is helpful when you want to restrict growth of an object while still allowing changes to current properties.
JavaScript provides methods to check if an object is frozen, sealed, or extensible:
console.log(Object.isFrozen(student)); // false
console.log(Object.isSealed(student)); // false
console.log(Object.isExtensible(student)); // false
These checks help you verify the protection level applied to an object.
Note that freezing, sealing, or preventing extensions only applies to the object itself, not to nested objects. For deep immutability, you must recursively apply protection:
const student = {
name: "Isha",
address: { city: "Patna", state: "Bihar" }
};
Object.freeze(student);
student.address.city = "Delhi"; // Allowed, nested object is not frozen
console.log(student);
Output:
{ name: 'Isha', address: { city: 'Delhi', state: 'Bihar' } }
To fully protect nested objects, you need a recursive function to freeze all levels.
Assuming Object.freeze() also freezes nested objects
Trying to add or delete properties on frozen or sealed objects without understanding strict mode behavior
Using protection on objects that require frequent structural updates
Forgetting that protection only affects the object, not its prototype
Use Object.freeze() for constant configuration objects
Use Object.seal() when updates are allowed but new properties should not be added
Apply protection thoughtfully in shared objects to avoid unintended restrictions
Consider recursive freezing for deep immutability
Verify protection status using Object.isFrozen(), Object.isSealed(), or Object.isExtensible()
Protecting configuration settings in applications
Preventing changes to constant objects in libraries or frameworks
Enforcing immutability in functional programming
Securing objects in multi-developer projects to avoid accidental modifications
Managing state in frontend applications such as React or Vue
const config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
Object.freeze(config);
config.timeout = 6000; // Ignored
console.log(config);
const student = { name: "Priya", age: 22 };
Object.seal(student);
student.age = 23; // Allowed
student.grade = "A"; // Not allowed
console.log(student);
const student = { name: "Saanvi", age: 21 };
Object.preventExtensions(student);
student.age = 22; // Allowed
student.city = "Patna"; // Not allowed
console.log(student);
function deepFreeze(obj) {
Object.freeze(obj);
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
deepFreeze(obj[key]);
}
}
return obj;
}
const student = {
name: "Isha",
address: { city: "Patna", state: "Bihar" }
};
deepFreeze(student);
student.address.city = "Delhi"; // Ignored
console.log(student);
JavaScript object protection methods, including freeze, seal, and preventExtensions, allow developers to control how objects can be modified. These methods help maintain data integrity, enforce immutability, and prevent unintended changes, which is especially important in large or shared applications. By understanding the differences between these methods, handling nested objects carefully, and following best practices, you can write safer, more maintainable, and robust JavaScript code.
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
