![Cover image for Object.freeze() Goes Hard 🥶❄️](https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpp23zqkyid9gghrurmbz.png)
The title says it all. Let's talk about one of JavaScript's most underrated features: Object.freeze(). This powerhouse of immutability isn't just a...
For further actions, you may consider blocking this person and/or reporting abuse
Great writeup! I think TypeScript makes Object.freeze a bit redundant though. You can annotate props as readonly which will cause a type error, and the
as const
will also work with keyof.But without TS, Object.freeze can definitely save your butt!
While TypeScript's
readonly
is great, Object.freeze() provides runtime protection that type-level immutability can't catch. This is especially important for:I see them as complementary tools - TypeScript for compile-time safety and Object.freeze() for runtime guarantees
Re #3, as you mentioned in the article, it doesn't deep-freeze, only shallow freezes, unless I don't understand something here.
For example:
I just wanted to correct this one mistake, #3, readonly can't "freeze" nested objects. I found this nice piece of code somewhere.
Along with your previous example, the following shouldn't work.
I used it myself to protect against any accidents. I needed to keep the state immutable, so I had a method to deep copy, cast to the mutable object, make the changes, then cast it back to being immutable.
This is why I prefer Rust.
wasm your way out 😂
Rust on the web?
Nice.
About
safeFreeze()
- couldn't this approach trigger issues in production (e.g. runtime mutations) which the developer wouldn't catch in their dev environment, and make it harder to identify and debug the issue once it occurs?Was this article supposed to be about JavaScript or TypeScript? As far as I know, the example syntax
is only valid for TypeScript code. However, the article continuously spoke about JavaScript. Which way is it on reality?
The solution to a problem which never exists... If you mutating event or default state or something then you make something obliviously wrong....
@mattlewandowski93 Thanks a lot for share this practicals uses of Object.freeze!
Unfortunately Object.freeze comes with hefty performance penalty
docs.google.com/document/d/1X6zO5F...