π§ Object.freeze() in JavaScript β Make Your Data Read-Only

In JavaScript, objects are mutable by default β which means you can change their properties any time.
But what if you want to protect your object from changes?
Thatβs where Object.freeze()
comes in.
π§ͺ Basic Usage
jsCopyEditconst user = {
name: "Nora",
role: "Developer",
};
Object.freeze(user);
user.name = "Lina"; // β Won't work
user.age = 25; // β Won't be added
console.log(user.name); // "Nora"
console.log(user.age); // undefined
π Important Notes
Object.freeze()
makes an object immutable (no add, delete, or update).It only works on the top-level properties.
Nested objects are not frozen!
jsCopyEditconst data = {
info: {
city: "Gaza",
},
};
Object.freeze(data);
data.info.city = "Ramallah"; // β
Still works!
console.log(data.info.city); // "Ramallah"
To deeply freeze an object, you need a helper function (e.g., recursive freeze).
π§ When to Use It
π Prevent accidental data mutations
π§ͺ Ensure constant config objects stay unchanged
π Improve code predictability and debugging
β Summary
Object.freeze()
= shallow immutabilityUse it to lock down objects
Be careful with nested structures
Subscribe to my newsletter
Read articles from Noura Mostafa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Noura Mostafa
Noura Mostafa
π Aspiring Full-Stack Developer Blogger π¨βπ» Passionate about web development and coding. βοΈ Sharing my journey through tech via CodeOdyssey π "The code is a journey, not a destination."