Skip to main content

Harshal V. LADHE

Deep Freeze Objects in JavaScript

Recursively lock every object level for true immutability
Published at:
Last updated:
Estimated reading time:3 min read
Promotional digital graphic showing the phrase ‘JavaScript deepFreeze()’ with code-themed visuals and design elements aligned to the left.(opens full-size image in a new tab)
Freezing a JavaScript object and every object nested inside it.

Introduction

Sometimes you want a JavaScript object to be completely immutable, including all nested objects. The built-in Object.freeze() only locks top-level properties, leaving nested objects mutable.

This snippet provides a production-safe deepFreeze(obj) function that recursively freezes an object and all its nested objects or arrays — ensuring true immutability and predictable behavior.

Deep Freeze Utility

function deepFreeze(obj) {
  if (obj && typeof obj === "object") {
    Object.getOwnPropertyNames(obj).forEach((prop) => {
      const value = obj[prop];
      if (value && typeof value === "object") deepFreeze(value);
    });
    return Object.freeze(obj);
  }
  return obj;
}

Highlights

  • Works on objects and arrays.
  • Standalone function, no prototype pollution.
  • Safe to use in production applications.

How It Works

  1. Checks if the value is an object or array.
  2. Iterates over all own properties using Object.getOwnPropertyNames().
  3. Recursively freezes any nested objects or arrays.
  4. Applies Object.freeze() to the current object.
  5. Returns the frozen object.

This ensures all levels of the object tree are immutable, preventing accidental mutations.

Example Usage

"use strict"; // Required to throw errors on illegal assignments

const user = {
  name: "Alice",
  preferences: {
    theme: "dark",
    language: "en"
  },
  roles: ["admin", "editor"]
};

// Recursively freeze the object
deepFreeze(user);

// Attempt to modify top-level property
user.name = "Bob"; // Throws TypeError in strict mode

// Attempt to modify nested object
user.preferences.theme = "light"; // Throws TypeError in strict mode

// Attempt to modify nested array
user.roles.push("viewer"); // Throws TypeError in strict mode

console.log(user);
// Output remains unchanged:
// { name: "Alice", preferences: { theme: "dark", language: "en" }, roles: ["admin", "editor"] }

Use Cases

  • Immutable configuration objects: Prevent accidental changes to app settings.
  • Library defaults: Freeze default options so consumers cannot mutate them.
  • Security-sensitive data: Ensure critical objects remain unchanged.
  • State management in front-end frameworks: Enforce immutability to prevent unexpected re-renders.
  • Immutable Redux states: Protect state objects from accidental mutations.
  • Shared objects in multi-module applications: Safely share objects without risk of modification.

Notes & Tips

  • Strict Mode Required for Errors: Without "use strict", assignments fail silently.
  • Performance Consideration: Recursively freezing deeply nested objects has O(n) complexity — avoid freezing very large objects in performance-critical paths.
  • Nested Arrays: The utility handles arrays seamlessly.
  • Production Safety: Standalone function avoids modifying Object.prototype, eliminating prototype pollution risks.
  • Alternatives: For large-scale applications, consider libraries like immer for immutable state management.
  • Debugging: Frozen objects throw errors on modification attempts, making bugs easier to catch early.

Frequently Asked Questions

Key Takeaway

The deepFreeze(obj) utility ensures your objects are truly immutable at all levels, providing safer, more predictable JavaScript applications and robust state management without the risks associated with modifying Object.prototype.

Changelog

  • — Added cross-reference to tutorial 'Native JavaScript Set Methods: union, intersection and difference'
  • — Added Frequently Asked Questions section
  • — Initial publication
This snippet is licensed under CC BY 4.0 by the author.

Share this snippet

Spotted a mistake or something outdated in this snippet? Suggest a correction.

  • Encapsulation with Private Class Fields

    Use native #private syntax to protect class properties in JavaScript.
    Implement native engine-level privacy in your OOP structures using ES2022+ private class fields and memory-efficient prototype methods.
    Published at:
  • First N Matches from Any Iterable with filter() and take()

    Get the first N matches and stop reading.
    Return the first N matches from any iterable with Iterator.from(), filter() and take(), stopping as soon as it has enough, even on infinite sequences.
    Published at:
  • JavaScript Spin-Wait Lock with Atomics.pause()

    Spin briefly with Atomics.pause(), then block with Atomics.wait().
    A copy-paste JavaScript spin-then-sleep lock using ES2027 Atomics.pause() and Atomics.wait() over a SharedArrayBuffer, with Node.js and browser worker examples.
    Published at: