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?
1 Answer
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
abstraction/encapsulation.