Frozen array / object syntax

It would be nice to be able to declare an object or array as frozen at declaration time.

I have no strong opinions on actual syntax, so I'll use one I've seen elsewhere on this board: {# #} and [# #]

I think this will be helpful on a number of levels:

  1. I assume this would help JS engines optimize storage of an object if they know it is read-only from creation, rather than relying on Object.freeze after the unfrozen object has been created.
  2. It would make declaring recursively frozen objects/arrays more readable and easier to declare:

const foo = {# contents: {# one: 1, two: 2 #}, values: [# 1,2,3 #] #}

as opposed to
const foo = Object.freeze({ contents: Object.freeze({ one: 1, two: 2 }), values: Object.freeze([ 1,2,3 ]) }

  1. This could propagate up to other languages like typescript, which could infer readonly on the declared object properties directly, rather than having to depend on wrappers like Readonly<>

Here's a related proposal: GitHub - keithamus/proposal-object-freeze-seal-syntax: A JavaScript TC39 proposal for Object.freeze & Object.seal syntax

The above proposal seems to add pretty much exactly what you want.

There's also a record/tuple proposal, which is perhaps getting some more steam, that'll also let you have immutable objects of sorts, but they behave in a different way: GitHub - tc39/proposal-record-tuple: ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!

oh excellent. Yes this is exactly what I was hoping for. Thanks for the pointer!

1 Like