Hacker News new | ask | show | jobs
by munro 3958 days ago
Immutability for stateful things seems unintuitive at first, but reframed as the lack of mutability, it makes more since. We can easily add it.

    yourCar === neighboursCar; // false
    yourCarRepainted === yourCar; // false :(
In the article's examples, how does the program know which object is different? It's weaved into the language design that every object has an address. That means if we want to write code without mutability, the interpreter has no idea since mutability is always on, and can't protect from accidentally modifying intentionally stateless code.

Flip side, if immutability is the default, we can easily add state, since it's just a lack of an address. The address becomes part of the data structure, giving the coder more power, since it's not locked outside of the code. Think SQL! Or Haskell!

    var yourCar = {id: 'my_car', color: 'red'},
        neighboursCar = {id: 'neighbours_car', color: 'red'};
    
    function referenceEqual(a, b) { return valueEqual(a.id, b.id); }
    
    referenceEqual(yourCar, neighboursCar); // false :D
    var yourCarRepainted = Object.assign({}, yourCar, {color: 'red'});
    referenceEqual(yourCar, yourCarRepainted); // true :D
Notice we've now flipped the address into our data, and even the (===) operator in our hands. With JS, this will run slowly since it can't infer our immutability, but constants are coming!