Immutability and objects

Praveen.
2 min readJul 11, 2017

--

In Javascript, as we all know the data types like numbers, strings and Boolean are used by value, and objects on the other hands are used by reference.

A brief on objects

With object we can change the value of the object by changing its properties. When we compare objects, we are essentially comparing the address where the object is stored, not the actual values. There is no “deep” comparison operation built into JavaScript, which looks at object’s contents, but it is possible to write it yourself

var object1 = {value: 20};
var object2 = object1;
var object3 = {value: 20};

console.log(object1 == object2);
// → true
console.log(object1 == object3);
// → false

What is immutability and why it is needed ?

Immutable means “something that cannot be altered” . This is what it means in terms of javascript also, every variable is stored at some physical location, that is every variable has an address. The value at that address cannot be changed. It is immutable.

Example :

var str = “Hello world!”;
var res = str.slice(1, 5);

Here, the slice method do not alter the value stored where “str” is stored, it actually returns a new string and that is assigned to “res”.

In fact, numbers, strings and Booleans are all immutable.

But, In case of arrays and objects, one can alter the value which means they are mutable.

var obj1= {val: ‘Obj is here’}

obj1.name = ‘obj1’;

console.log(obj1);

// Prints {name: obj1, val: ‘Objs is here’}

Objects and arrays are all mutable.

How to make arrays or objects mutable ?

This is a big question and this is a very common need. This is a fundamental behind React/Redux to ensure that one of the pillars of redux ‘state’ which is essentially an object should always be immutable.

There are many ways to achieve this :

  1. Using custom libabry like immutableJS by facebook that helps us achieve this.
  2. Using Object.assign() [ES6 feature]

const person = {name: ‘John’, age: 28 }

const newPerson = Object.assign({}, person, {age: 30})

console.log(newPerson === person) // false

console.log(person) // { name: ‘John’, age: 28 }

console.log(newPerson) // { name: ‘John’, age: 30 }

Yeah That’s all.

Happy immutating folks !!

--

--