Freeze and Seal Objects in JavaScript

Adnan Ahmed
4 min readDec 25, 2020

Variables we declare in javascript with the help of const, are not purely constant. Let's say that if we have a variable called config with a bunch of properties and if we print it to the console you will see it has a name and a database object.

const config = {
name: "module-account",
database: {
host: "127.0.0.1",
port: "2020",
username: "admin",
password: "r@@t",
},
};
console.log(config); // {"name":"module-account","database":{"host":"127.0.0.1","port":"2020","username":"admin","password":"r@@t"}}

But if we update the value of let’s say name to be xyz, you will see you can do that. Although it's a constant.

config.name = "xyz";console.log(config.name);   // xyz

To prevent this javascript comes with a bunch of methods, such as Object.freeze, Object.seal and Object.preventExtensions. Which we can use to make them immutable. Let's look at the examples to understand how they work and how we can use them in our codebase.

Object.freeze

If we freeze an object, let’s say Object.freeze(config) and print the name you will see that we are still able to read the value from the config.

Object.freeze(config);console.log(config.name);       // xyz

But if we try to update any of the existing values, let’s say config.name is abc, we will get the…

--

--

Adnan Ahmed

A software engineer sharing insights and experiences through blog posts. Delving into technical topics and occasional general musings. https://adnanahmed.info