🧊 Object.freeze() in JavaScript β€” Make Your Data Read-Only

Noura MostafaNoura Mostafa
1 min read

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 immutability

  • Use it to lock down objects

  • Be careful with nested structures

0
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."