JS’s objects are so beautiful: we can copy them, change and remove properties and do many cool things.
However, it’s always good to remember:
What’s wrong with mutability?
We can see that: although we are creating a new object, the
user one was modified. This happens because when you assign a new value to an existing object, you are just assigning a memory reference to it.
Come to the Immutable side of the force
Immutability is the art of maintaining the state of an object, making development simple, traceable, testable and decreasing any possible side effects. The main idea is: an update should not change the object, but create a new object with the updated data.
We can achieve immutability through pure functions, aka functions that will always return a given value if provided with the same input values. Neat, right? See this example:
Here we have a
user object and its
changeName function. You can see that, given the initial user and the new name, the initial object isn’t updated, and we always have the same result.
Creating Pure Functions and Removing References
Okay, we already know what can happen if we change the object’s state, now we need to know how to work with objects without causing side effects.
There are some ways to make immutable objects, but the most recommended approach to create them is using the Objects API and the ES6 destructuring assignment. We could also use functions like
.reduce to accomplish the same task.
Here at Cheesecake Labs we use Redux and ImmutableJS to accomplish pure and functional Front-end projects, keeping our code clean and easy to read.
Originally published at cheesecakelabs.com on March 16, 2017.