Understanding concepts of immutables and mutables in javascript

  Javascript strings are immutable.But javascript objects and arrays are mutable.A mutable object is an object whose content can be modified after it is created. An immutable object is an object whose content cannot be modified after it is created. Consider an the following example

Now,from the above we realize that arrays and objects in javascript are mutable,ie they can be mutated. Functions like slice returns a new reference and does not modify the original array. Example

filter(),map(),reduce()  are the other functions that does not modify original array. Javascript es2016 brings a new operator called spread operator.Spread operator helps copy a array to a new array with new reference.

Usig spread operator(…a) along operations like slice,filter ….. helps operate with javascript arrays in an immutable way. Spread operator on object

Why Immutability? We look at  immutability from an angular point of view to get a better understanding of the needs if immutability and the reason why it increases performance.Consider we have a parent component and child component.From the parent component an object is shared to the child component.Lets say the following is the object is the one that is shared

Consider a click event function…

Spread syntax(…) in JavaScript(ES6) – Explained

Spread syntax helps to expand iterables (Arrays, Objects, Strings) in places where zero or more entities are expected. Consider an example with array.

Here 3 arguments are expected and we store them into an array

Now we use spread syntax to provide arguments in the array

The expected result is 6     Now while working with spread syntax on objects Merge two objects with spread syntax.

For cloning the object

    Now working with spread syntax on strings Strings are also iterable and using spread operators will make them spread into individual characters.

JavaScript objects and arrays are mutable. If you assign a JavaScript array into another variable and push a value into it, both the first one and second one will change. Actually, this is happening because both the variables have the same reference. See the example below

In the above example, a new number,5 is pushed into the array. Here you can see both the variables have changed because both have the same reference. The spread operator creates a new copy of the array with different reference. Using the spread(…) operator we can achieve what we need without this…

Share this page in social media platforms