Search code examples
javascriptimmutability

What are the usecases for Object.freeze() and Object.seal() in JavaScript?


I've done some searching and found that JavaScript objects can be frozen or sealed, meaning that they cannot be modified or have new properties added to them, respectively.

I understand what these methods do, but not why one would ever want to use them in a codebase.

One guess I have for why to use freeze() is to prevent errors in the category of accidental modification of variables: declaring variables with const by default prevents a lot of such errors (though const only applies to bindings, and not variables themselves) and imposes very little syntactic burden. On the other hand, calling .freeze() on every declared object seems like it would be deeply impractical, and I haven't ever seen a codebase do this.

However, I don't have even a viable guess for when to use seal().


Solution

  • The difference between (const) variables and (frozen) objects is that the former are local while the latter are often passed around through the entire application. Accidental modifications are much easier if people don't agree on the expectations whether an object should be mutable or not. Often enough, modifications are ok however, the entire paradigm of OOP relies on objects changing state and communicating with each other (through messages, be that method calls or setter invocations). Getting "your" objects modified is the norm, and allows other parts of the code to customise them as necessary. This is why you have not seen codebases where every object is frozen.

    You would however freeze objects when your code relies on them being immutable, and doesn't trust other code to keep up that invariant. If bad things would happen, you'd rather get an exception when attempting to modify the object and find that bug immediately, instead of having a wrong value causing havoc down the road without clear provenience.

    And yes, this is more common than you might have thought, functional-programming-oriented libraries often (deep) freeze objects, at least in development mode, so that buggy code is discovered as soon as possible.