-3

Why use getters instead of normal functions in JavaScript? Because they perform the exact same thing. What are the differences between a getter and a normal function in JavaScript?

2
  • Uh, can you show how you can achieve with a normal function what a getter does? Commented Jan 30, 2020 at 7:30
  • for abstraction/encapsulation. Commented Jan 30, 2020 at 7:31

1 Answer 1

1

The get syntax binds an object property to a function that will be called when that property is looked up.

const obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    if (this.log.length == 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
}

console.log(obj.latest);
// expected output: "c"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.