Are `getter` and `setter` necessary in JavaScript?

Are getter and setter necessary in JavaScript?

Necessary is a bit of an undefined word. Any problem can be solved without a getter and setter (usually by changing the interface to methods instead of direct property access), just like any problem can be solved without a for loop (by substituting a while loop and manually maintained loop variables), but both are useful features to have in a programming language because when they are a match for a use case, then they are the cleaner and more convenient way to program. Thus, they are “useful” and “helpful”.

A getter or setter can be very useful at times, but they only need to be used when their specific functionality is required – otherwise plain property access without a getter or setter can be just fine.

A getter has use when you want to run some code every time a property is requested. In your example, the getter always returns an uppercase version of the name regardless of what the case of the name is, while reserving the actual case for internal use.

A setter has use when you want to run some code every time a property is set. In your case, it prevents the setting of a falsey name. You can’t implement either of those features without a getter/setter.

Direct property access is a perfectly fine way to do things when you don’t need getter or setter special logic.

It’s also possible that getters and setters may get and set some property that is not publicly available (so not available at all via a normal property access), either because it’s stored somewhere differently (not as a property on this object) or stored privately or even that it’s stored else such as in some hardware device. In these cases, the getter and setter simulate the value being in a property when it actually isn’t. So, they simplify the interface while allowing the actual value to be stored or retrieved from anywhere.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)