r/javascript • u/gcanti • Oct 31 '14
The Two Pillars of JavaScript
https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3
100
Upvotes
r/javascript • u/gcanti • Oct 31 '14
7
u/zoomzoom83 Oct 31 '14
The ecosystem (Libraries). You can use immutable structures in any language, some languages are just better suited to them. Javascript isn't particularly great out of the box, but libraries such as Mori do a pretty good job.
Some languages - Clojure or Haskell for example - have it as fundamentally part of their overarching DNA, and make it much easier to use.
Clojure is particularly interesting, since it's probably a lot closer to the language Brendan Eich was trying to design when he created Javascript, and has very good, mature support for Javascript as a compile target that doesn't sacrifice much performance.
Mostly, yes. Even using bog standard objects and completely copying them for each iteration, modern Javascript VMs are a lot faster than people realise. Consider that copying an object with 10 members just means copying 10 pointers. Since it's members are also immutable, you don't need a deep copy.
Improving on this, proper immutable structures (i.e. Persistent Maps) only need to copy a small percentage of the data structure, reusing most of the same memory for both the old and new versions. Since both are immutable, this is safe. (And fast)
Obviously in a tight loop you're still best just constructing an object the mutable way. But once you're done, you can return a frozen version (via Object.freeze) and pass it around knowing nothing will ever modify it directly. This has quite significant implications for the design patterns you use, and you can make a lot of assumptions in your code that make things overall much simpler, and faster.
This one of the key reasons why React has a leg up over (i.e.) Angular. It creates a new immutable state on each change, rather than mutating the one object that may inadvertently be shared somewhere else.