-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?

Sayan Sahoo
  • 65
  • 1
  • 4

1 Answers1

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

Nourhan Ahmed
  • 179
  • 1
  • 10