DEV Community

Oliver Mensah
Oliver Mensah

Posted on

Obtaining immutable operations with native ES6 function.

Mostly we write programs that deal with changing data.The way we change values of variables can lead to unexpected bugs in a software project. If you are dealing with primitive data types then there is no need to worry. In cases where you are working with referential data types, then care must be taken to avoid unnecessary bugs.
Let's look at the code below:

From the above code, b references a primitive value. We then assign c to the same value as b. The value of c was change and it did not affect that of b because both are primitive types and changes affect the values.

Unlike variable m and n. we assign m to n and the change made to n affects m. This is because arrays are non-primitive hence they are copied to the same reference object, so changes will affect each other.

You might want to have a copy of m for n and we can change one without affecting the other. Some solutions like using immutable data structures created by Immutable.js or using JavaScript libraries such as Underscore and Lodash to execute immutable operations.

ES6 brings on board native functions to execute immutable operations and that is the solution we will use to solve the mutability issue of object assignments.

NB: Please Read and critique on how the article can be made better.

Top comments (2)

Collapse
 
joelnet profile image
JavaScript Joel

Object.assign is a great way to create shallow copies of an object. You can also combine this technique with Object.freeze if you want to force immutability.

var m = Object.freeze([2, 5])
m.push(6)
// > ERROR: Can't add property 2, object is not extensible.

Collapse
 
olivermensahdev profile image
Oliver Mensah

Ok. Great