JavaScript Object freeze() - Make Object Immutable

Updated on December 2, 2024
freeze() header image

Introduction

The Object.freeze() method in JavaScript is a powerful tool for making an object immutable. Once an object is frozen, you cannot add, delete, or modify its properties. This functionality is particularly useful in functional programming where immutability is a preferred characteristic to avoid side effects and maintain state integrity.

In this article, you will learn how to effectively use the Object.freeze() method to make JavaScript objects immutable. Explore various examples and understand the implications of freezing objects, including nested objects and effects on the object’s enumerability, configurability, and writability.

Understanding Object.freeze()

Basic Usage of Object.freeze()

  1. Start with a simple object.

  2. Apply Object.freeze() to prevent any modifications.

    javascript
    const obj = { name: "John", age: 30 };
    Object.freeze(obj);
    

    Attempting to change the name property or add a new property to obj will have no effect.

Attempting Modifications on a Frozen Object

  1. Test if modifications to a frozen object result in errors or silent failures.

  2. Try modifying, adding, and removing properties.

    javascript
    obj.name = "Jane";  // This will not change the value
    obj.height = 180;  // This property will not be added
    delete obj.age;  // This will not remove the property
    console.log(obj);
    

    After freezing, the object remains unchanged despite the attempt to modify it. JavaScript in strict mode throws an error while in non-strict mode, it fails silently.

Deep Freezing Objects

Creating a Deep Freeze Function

  1. Understand that Object.freeze() is shallow and does not apply to nested objects.

  2. Implement a recursive function to freeze an object deeply.

    javascript
    function deepFreeze(object) {
        Object.keys(object).forEach(prop => {
            if (typeof object[prop] === 'object' && object[prop] !== null) {
                deepFreeze(object[prop]);
            }
        });
        return Object.freeze(object);
    }
    

    This function iteratively applies Object.freeze() to all nested objects, ensuring complete immutability.

Applying Deep Freeze

  1. Create a nested object.

  2. Use the deepFreeze() function to freeze the object deeply.

    javascript
    const user = {
        name: "John",
        preferences: {
            theme: "dark"
        }
    };
    deepFreeze(user);
    user.preferences.theme = "light";  // This will not change the theme
    console.log(user);
    

    The change to theme is not reflected, demonstrating that the deep freeze was effective.

Conclusion

The Object.freeze() method in JavaScript serves as a critical function for enhancing data integrity by making objects immutable. Utilizing this method prevents accidental data changes that can lead to bugs and inconsistent states in your applications. Through the examples and the deep freeze function provided, adapt techniques to handle both simple and complex objects, ensuring robustness in your JavaScript projects. Implement these practices in development to create more predictable and maintainable code.