skip to Main Content

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


  1. 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 a computed property, more like a property.

    Login or Signup to reply.
  2. From MDN explanation:

    While using the get keyword and Object.defineProperty() have similar
    results, there is a subtle difference between the two when used on
    classes.

    When using get the property will be defined on the instance’s
    prototype, while using Object.defineProperty() the property will be
    defined on the instance it is applied to.

    Get keyword is better used in classes.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search