#CodeNewbie

#CodingTips

#Frontend

#Fullstack

#JavaScript

#LearnToCode

#Programming

#WebDevelopment

JavaScript Object.freeze(): Protect Objects from Mutation

JavaScript objects are mutable by default. While flexibility is powerful, it can also lead to bugs when shared data is modified unexpectedly.

`Object.freeze()` helps lock objects down.



## 🔹 What Is `Object.freeze()`?

`Object.freeze()`:
- Prevents adding new properties
- Prevents removing properties
- Prevents changing existing values

```js
Object.freeze(obj);

The object becomes immutable at the top level.



🔹 Basic Example

const settings = { theme: "dark" };
Object.freeze(settings);

settings.theme = "light"; // ignored
settings.layout = "grid"; // ignored

No error in non-strict mode, but no changes happen.



🔹 Freeze in Strict Mode

"use strict";
settings.theme = "light"; // ❌ TypeError

Strict mode throws errors for invalid mutations.



🔹 Shallow Freeze (Important!)

Object.freeze() is shallow.

const state = {
 user: { name: "Vu" }
};

Object.freeze(state);
state.user.name = "Alex"; // ✅ allowed

Nested objects remain mutable.



🔹 Deep Freeze Pattern

function deepFreeze(obj) {
 Object.values(obj).forEach(value => {
   if (typeof value === "object" && value !== null) {
     deepFreeze(value);
   }
 });
 return Object.freeze(obj);
}

Use this carefully for complex data.



🔹 freeze() vs seal() vs preventExtensions()

Method                      Add    Delete    Modify
freeze()                        ❌      ❌           ❌
seal()                            ❌      ❌           ✅
preventExtensions()    ❌      ✅           ✅

Choose based on your needs.



🔹 Common Use Cases
    •    App configuration objects
    •    Constants and enums
    •    Shared library defaults
    •    Defensive programming



🔹 Common Mistakes

❌ Assuming deep immutability
❌ Freezing large, frequently updated objects
❌ Using freeze instead of proper state updates



🔹 Best Practices
    •    Use freeze for configs, not state
    •    Combine with immutability patterns
    •    Prefer shallow freeze unless necessary

✅ Recommended:

const CONFIG = Object.freeze({ api: "/v1" });



🎯 Final Thought

Immutability is about control, not restriction.
Object.freeze() protects your data from accidental damage.