Hi Guys,

In this blog I would like to explain how you can create immutable object in JavaScript.
First of all we should understand what is mutable and immutable objects. I will try to explain it with some examples.

Mutable Object:

var obj = {
    name : "Somebody"
}

var obj_new = obj;
obj.name = "Nobody";

console.log(obj.name); // Nobody
console.log(obj_new.name); // Nobody
console.log(obj === obj_new); // true

Here we see that for mutable values, changing value in one place changes it for all reference to that object. But in case of immutable object changing values or state should not allow any change in object.

Immutable Object:

var obj = {
    name: "Somebody" 
}

Object.freeze(obj);
obj.name = "Nobody";
console.log(obj.name); // Somebody

Now in this case when we use Object.freeze(), the freeze applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. In case of properties are object itself  then those  object are not frozen and may be targeted to be changed.

In this case you need to implement recursive function which makes all inner objects immutable.

Shallow freeze:

function freezeAll(obj) {
  var properties = Object.getOwnPropertyNames(obj);  
  for (prop of properties) {
    var val = obj[prop];

    if(typeof val === "object"){
        freezeAll(val)
    }else{
        obj[prop] = val;
    }
  }

  return Object.freeze(obj);
}

var o = {
  a: {
    b: "3"
  }
};

freezeAll(o);
o.a.b = 10;
console.log(o.a.b);

 Good Day :)