Hacker News new | ask | show | jobs
by ionforce 4347 days ago
Immutable objects in general or immutable objects in JavaScript specifically?
1 comments

A general example would be good :)
It is a guarantee to you that the data structure has not been tampered with by the time it reaches you.

    // pseudo code

    var fruitBasket = new FruitBasket('banana, 'apple)

    muckWithFruits(fruitBasket)
    suspiciousLogger(fruitBasket)
    weirdCallback(fruitBasket)

    // here
    assert(fruitBasket.length == 2)
By the time we reach "here", we know that none of the functions since the inception of fruit basket have tampered with it.

This may not be a big deal if you are disciplined about never modifying your source data, but this moves the guarantee from a soft one to a mechanical one.

And then there's all this typical stuff about functional programming blah blah... But that's the most practical example I can think of.

If everything is immutable, it also makes it a lot easier to parallelize tasks, because you can easily deduce a dependency graph.
In multi-threaded environments, immutable objects are thread-safe. When multiple threads are sharing data, you would normally have to worry about synchronization. However, immutable data structures guarantee that the shared data will not change, so synchronization issues simply go away.

That said, I'm not sure how this applies to JS, which is single-threaded.

Even though it's single-threaded (not with web threads maybe?), it can still be asynchronous, which is where the issues really lie.