Web Developer Interview Preparation

Immutability in JavaScript

Definition Immutability is an important concept, and it means that an element is unchangeable. But the meaning of immutability in JavaScript is a little bit different than other languages. What’s not immutability in JavaScript ‘const’ is not about immutability! We have a new keyword called const in JavaScript version 6, and it seems like making an unchangeable variable like what some other languages do. However, we can change the values of an element in an array using the following notation.

const myArr = [1,2,3];
myArr[0]=6;
This works because arrays are assigned their reference, not to values. So, the elements in myArr can be modified even with the keyword ‘const’, and this happens a lot in JavaScript. Therefore, we should think ‘immutability’ as a concept, and we need to try to achieve this goal as we write our programs. Why is immutability important in JavaScript? Consider that we have a mutable array, and use the forEach method to add one to each element.
//MUTABLE
var myArr = [5,6,7];
myArr.forEach(function(item, index) {
  myArr[index] = item + 1;
});
console.log(myArr);
// [6, 7, 8]
The 'forEach' takes each element and transform it in the original array. It is a little bit dangerous as it could cause problems in a complex program. So it is better if we create a immutable function that does not modify the originals but works in a copy. Therefore we use the map function, which we studied in the previous blog post.
var myArr = [5, 6, 7];
function increase(item) {
    return item +1;
}
var modArr = myArr.map(increase);
console.log(modArr)
The map function is an immutable function that does not modify the original array. But it returns a new array that we can use in a variable. It is much safer way as it protect the original information. So the important concept with 'immutability' is that we need to create an immutable function to protect the original information (values) of the data! How does immutability work in JavaScript? Mastering Web developer Interview Code – Ray Villalobos, Lynda.com LINK]]>

Leave a Reply

Your email address will not be published. Required fields are marked *