Make Immutable JavaScript Objects Using Object.Freeze

Yes we can do this. The title seems pretty fascinating for developers and yes even we felt great when we learnt about Object.freeze method in JavaScript. Isn't that great that we make an object in JavaScript and stay assured that it won't be altered at all during run-time. Those who aren't aware about Object.freeze let's make you aware

object.freeze in javascript to make immutable objects

What is Object.freeze?

This is a method in JavaScript which was introduced in ECMAScript5 and it makes the object literally Immutable. This method takes an object as a parameter and return the frozen object. Following are the capabilities that are introduced into that object after freeze:
  • Properties can't be added
  • Properties can't be removed
  • Values of properties can't be altered
This method actually makes it possible to keep an object as a constant. Consider the below example

var cellphone = { name: "iPhone", 
                  model: 7,
                  price: "$649"};


Now in the above example, we have a JavaScript Object cellphone which has some properties like name, model & price. Now in the next line we have given this object as a parameter to Object.freeze() method.
From now on the object will be frozen and further on we can't add properties or alter values present in them.

Down below we have shown the outcome, for the above line of codes

var cellphone = { name: "iPhone", 
                  model: 7,
                  price: "$649"};


//Adding a new property as yearLaunched
cellphone.yearLaunched = 2016;

//Changing the value of price property
cellphone.price = "$659";

//Viewing the cellphone object again

//Object {name: "iPhone", model: 7, price: "$649"}

As you can see above, that browser may let you execute the command to change the properties or might throw up error in some browsers, but the object will stay the same as it was passed to Object.freeze method. So this way you can make your JSON object immutable.

Video Tutorial for Object.freeze()

You can try it up at your end, just open up your browser console and start experimenting. You will end up learning something new.

Happy Learning!!


Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started