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

1. Preventing Extensions with 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.

2. Sealing Objects with 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.

3. Freezing Objects with 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

4. Using Object.defineProperty() for Controlled Access

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

5. Deep Protection

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.

6. Notes and Best Practices

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

7. Summary of the Tutorial

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


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.


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