Any links to discussions around Object.deepFreeze?

In the tc39 notes from 2021/01/25 there was discussion around the mutability of JSON modules. It was mentioned that projects could opt-in to immutability with:

you can simply be the first importer and then you can freeze the object


Deeply freezing an object is non trivial (though easier when source object is known to have come from JSON), so is commonly done by importing a library.

Question: Does anyone have any links to previous discussions about adding Object.deepFreeze

Foreseen issues that have probably already come up:

  • Would it handle cycles?
    • Tracking cycles will consume more memory but avoids infinite loops
  • Would it freeze prototypes?
    • Should it visit just own properties?
    • Should it freeze Array.prototype when obj contains an array?
  • Would it be configurable?
    • It could take an argument similar to `JSON.stringify', an array of props to visit
  • Preference for using Record for deep immutability

EDIT: rephrased post as a question instead of an idea

Handling cycles seems like an obvious thing to do, but I don't think there's any reasonable choice to be made about freezing prototypes. If it does, then it could have unintended side effects far beyond the user's intention; if it doesn't, then it's not actually deeply freezing the object.


Is there much of a use case for deep freezing besides parsing JSON (either with JSON.parse, or with JSON modules)?

I could see cases where it might be convenient to deep freeze a nested object literal, but that gets dangerous if you ever want to add some mutable instance of a class to that nested structure. And tuples/records would remove this use case.

As an aside: The following code is a little slow, but would allow one to copy a data-only object and deep freeze it.

JSON.parse(JSON.stringify(data), (_, value) => Object.freeze(value))

I guess there are scenarios when you may be receiving a nested data structure from a library that you would like to freeze (i.e. maybe a request body while in node).

If we do implement a deepFreeze function, it could pave a standard way to implement other deep operations, such as deep cloning, or deep equality checking.

How about using GitHub - tc39/proposal-record-tuple: ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!?
We can convert a object to records-tuple.

1 Like

We can add Object.prototype.toImmutable function, so that we can gain

For Array, it's turn out to be tuple,
For Object, it's turn out to be record

FYI rephrased post as a question, not a proposal.