Immutable Javascript

There are very good reasons to use immutable objects in certain languages. In Javascript however I’m still kinda meh. What are immutable objects? Basically it means that you are always creating new objects or entire data structures instead of making individual changes to objects in the same data structure.

The biggest reason for immutable objects is that they’re thread safe. This may make sense in some languages but since javascript is single threaded this doesn’t really apply. And when you use web workers to take advantage of multi-threading you’re using a messaging interface that helps to keep you out of trouble with the state of your objects.

Other arguments for immutable objects are to avoid temporal coupling and defensive copying.  Temporal coupling is an anti-pattern in which two actions are bundled together into the same just because they happen to occur at the same time. However, you can just as easily avoid it with either mutable or immutable objects. I don’t get the ‘no defensive copying’ argument because with immutable objects you ARE creating a complete copy.

Facebook’s React is a popular view framework that’s the V in MV*. They also have a library for models called immutable.js.  For React it makes some sense to use immutable.js.  React uses the observer pattern to update the view on a change to it’s model. Whether you like React or not there is some simplicity in not having to write specific binds between the model and view.  And the expensive process of observing all objects isn’t impacted by replacing the entire model through immutable.js.  There can also be some marginal performance improvements with this particular stack. With other MV* libraries however, you already have a model with its own methods and way of binding the view to the model. I think immutable javascript makes some sense for React apps but only depending on the application. Sometimes native objects make more sense for React apps, not just for performance, but because you can use native arrays with a much more extensive list manipulation library like lodash.js

In conclusion I’m really not sold on immutable objects in javascript, except in certain React apps.




Leave a Reply