DEV Community

Discussion on: Immutable Arrays and Objects in JavaScript, the Native Way

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Agreeing not to mutate data doesn't make the data immutable; someone else can still come along and mutate our data, or we might do so ourselves by simply missing a mutation somewhere.

This doesn't only affect us, but also the language: when no data is actually immutable, it's harder to do optimisations like copy-on-write that make many functional languages more performant.

Collapse
 
mindplay profile image
Rasmus Schultz

Given that, yes, nothing makes an array immutable, I think the point of this article was to show what you can do under that constraint - short of inventing new collection types, which is it's own bag of worms, a commitment not to mutate is the next best thing.

We generally have control of what we do within the boundaries of our own modules, and I tend to prefer immutable operations mainly because it makes testing easier. As with any form of side effects, that requires discipline, which, yeah, that's not great, but under the circumstances, it's better than the alternative of making more of the kind of mess you get with JS standard types like Array.

For example, if my function is going to sort an array, I generally slice() before I sort, just in case. Yeah, that wastes CPU time and memory - in most cases not much though, as strings and objects don't get aggressively copied when you slice.

No big deal. And it means I ship pure functions that are easier to test and reason about. Programmer hours in most cases cost more than CPU time - avoid premature optimizations and so on. 🙂