JavaScript

coding learning websites codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Protection


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.

Why Object Protection Is Important

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.

Object Protection Methods

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()

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()

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()

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.

Checking Object Protection Status

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.

Nested Objects and Protection

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.

Common Mistakes

  • 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

Best Practices

  • 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()

Real-World Applications

  • 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

Practical Examples

Example 1: Freezing an Object

const config = {
    apiUrl: "https://api.example.com",
    timeout: 5000
};

Object.freeze(config);
config.timeout = 6000; // Ignored
console.log(config);

Example 2: Sealing an Object

const student = { name: "Priya", age: 22 };
Object.seal(student);
student.age = 23; // Allowed
student.grade = "A"; // Not allowed
console.log(student);

Example 3: Preventing Extensions

const student = { name: "Saanvi", age: 21 };
Object.preventExtensions(student);
student.age = 22; // Allowed
student.city = "Patna"; // Not allowed
console.log(student);

Example 4: Deep Freeze Recursive Function

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);

Summary of JavaScript Object Protection

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.


Practice Questions

  1. Preventing Extensions
    Create an object person with properties name and age. Use Object.preventExtensions() and try adding a new property gender. Log the result.

  2. 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.

  3. 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.

  4. Checking Extensibility, Sealed, and Frozen Status
    Use Object.isExtensible(), Object.isSealed(), and Object.isFrozen() on various objects to verify their protection status.

  5. 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.

  6. Non-Configurable Property
    Create a property on an object with configurable: false and attempt to delete or redefine it. Log the results.

  7. 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.

  8. 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.

  9. 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.

  10. Protecting Configuration Object
    Create a configuration object for an application and freeze it completely. Try changing top-level and nested properties to demonstrate immutability.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top