Why don't we have variable getters and setters?

I've been wondering why we don't have getters and setters to variables.
I get that it may be bad for performance and functions(or decorators) are better suited for this purpose.
so what's the reason??

This seems like something that would make code much harder to reason about and understand. What would be the use case?

1 Like

With property getters and setters it is clear to the reader who/what is responsible for handling the interaction.


In the above code, we are asking thing for prop. In very very abstract terms this could be seen as thing being the receiver of a message with the information GET: prop. Languages like Smalltalk are modelled closed to this.

Compared to:

abc; // triggers a getter?

With a plain symbol acting as a getter it’s less clear (IMO) that there is a separate receiver that is involved in the interaction.

Also. variable getter/setters do exist in JS but only when in sloppy mode, using a proxy as the receiver for a with block. So it can be done but is unlikely to be the cleanest solution to the problem the code is trying to address.

1 Like

Note for completeness' sake: side effects on variable get/set are also possible by adding getters/setters to the global object (not that it's a good idea)

Object.defineProperty(window, 'foo', {
  get() { console.log('foo getter ran') },
  set(_) { console.log('foo setter ran') }

That only affects global variables. It's also possible to do the same with with.

Neither are patterns that I'd want to see encouraged or expanded.

1 Like

Yes here is related proposal in the Future extension part of the decorator proposal. https://www.github.com/tc39/proposal-decorators/tree/master/EXTENSIONS.md

let decorators are precisely what i needed!
They can help in reactivity, validation and much more. I would like to see them included in the language some day.