1

Here I am using getter to get the value of language property.

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "en",
  get lang() {
    return this.language;
  };
};

document.getElementById("demo").innerHTML = person.lang;

The question is why do I need to use the getter if I can get the same result using this piece of code?

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "en",
  lang : function() {
    return this.language;
  };
};

document.getElementById("demo").innerHTML = person.lang();
Ara Galstyan
  • 486
  • 1
  • 4
  • 11
  • 3
    You **don't need** to use a getter. I'm not sure why you have this idea. It's ultimately your choice. – VLAZ Feb 02 '21 at 07:54
  • 1
    https://stackoverflow.com/questions/42342623/why-use-getters-and-setters-in-javascript – Muhammad Usman Feb 02 '21 at 07:55
  • 1
    At any rate, reasoning for getters is exactly the same as here [Why use getters and setters/accessors?](https://stackoverflow.com/q/1568091) (although in Java, they are still methods you execute). – VLAZ Feb 02 '21 at 07:55

0 Answers0