I have hard time understanding why there are two different ways to perform an absolutely identical operation in JavaScript objects.
Here I’ve got an object which contains an array in its "log" property. And the "latest" property of obj stores the last item of the array which is done with the help of a function.
const obj = {
log: ['a', 'b', 'c'],
latest: function () {
return this.log[this.log.length - 1];
},
};
console.log(obj.latest());
But then later in the tutorial the keyword Get is introduced and its existence kinda confuses me because it does the exactly same thing here:
const obj = {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
},
};
console.log(obj.latest);
They explained the get keyword provides simpler syntax by allowing to call "latest" like a regular property (obj.latest) as opposed to obj.latest() which is a method.
But is there anything more to it other than simplified syntax?
Thanks
3
Answers
A
Function
is what ever you want it to be, some parameters, some code, and some returning or none of these.But a
get
Function, is strict to no parameters, with return value. it’s acomputed property
, more like a property.From MDN explanation:
Get keyword is better used in classes.
The syntax is the main difference – and an important difference. Using a getter is indistinguishable from using a normal data property, they have exactly the same property access syntax.
This encapsulation of the object implementations in an interface allows decoupling the implementation of the object from its usage in other code, permitting seamless refactoring where you change back and forth between data properties and accessor properties. If you were using a function (i.e. getter and setter methods), you would always have to use calls instead of accessing the property by its name, leading to much boilerplate when having to wrap every data property access in an unnecessary method.