JavaScript Object Freeze Limitation: Shallow vs Deep Freeze

🚀 A JavaScript Mistake With Object.freeze() At first glance, this looks safe: const user = { name: "Inderpal", address: { city: "Noida" } }; Object.freeze(user); user.name = "Updated"; user.address.city = "Delhi"; console.log(user); You might expect nothing to change. But output will be: { name: "Inderpal", address: { city: "Delhi" } } Why? Because Object.freeze() only performs a shallow freeze. It prevents changes to top-level properties, but nested objects can still be modified. To truly make it immutable, you need deep freezing. function deepFreeze(obj) { Object.keys(obj).forEach(key => { if (typeof obj[key] === "object" && obj[key] !== null) { deepFreeze(obj[key]); } }); return Object.freeze(obj); } JavaScript often protects the surface, not the depth. Understanding shallow vs deep behavior prevents subtle state bugs. Have you ever assumed something was immutable when it wasn’t? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories