The Immutable.js library reached version 3.0.0 last week, adding a number of API changes. Immutable.js provides persistent data structures allowing for a functional programming style while using natural syntax familiar to traditional JavaScript developers.
In a sufficiently large JavaScript application, developers may find themselves running into issues with data changing in multiple places. One way to solve this change notification problem is to use the Object.observe
feature of EcmaScript 6. Immutable.js goes in the opposite direction by creating data structures that can't be changed, thus eliminating the possibility of change problems.
Its creator — Lee Byron, Interactive Information Designer at Facebook — made Immutable.js as a way to bring the "novel and powerful concept of persistent data structures made popular by other languages like Scala and Clojure to idiomatic JavaScript."
One of the structures is List
, which acts like a JavaScript Array.
var list1 = Immutable.List.of(1, 2); var list2 = list1.push(3, 4, 5);
In this example, list1
is not changed when values are pushed onto it. Instead, a new list is returned that contains the result of the operation, leaving the original unchanged.
list1: [1,2] list2: [1,2,3,4,5]
According to Lee, there are many problems that persistent data structures can help with:
These structures can help solve really tricky problems, and help push JavaScript towards a pure functional style and avoid scoped mutable state. Anywhere you find yourself making defensive copies of complex data, or modeling atomic transactional change sets, persistent data structures might help you out.
Lee mentioned that his library was inspired by the work done with mori which brought the persistent data structures of ClojureScript to JavaScript. In a discussion on Reddit on the differences between mori and Immutable.js, user DavetheBassGuy said:
Immutable.js fits better with the rest of the JS ecosystem in my opinion, because it is designed for and written in JS, rather than ClojureScript. The API follows the native Array API where possible, so it's a lot easier to switch between the two. It is even possible to write functions which work on both native arrays and immutable sequences, using map, filter, reduce, etc.
Minified and gzipped, Immutable.js is a 15K download. Ideas and pull requests are welcome on the GitHub repository.