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?
Asked
Active
Viewed 63 times
-3
-
Uh, can you show how you can achieve with a normal function what a getter does? – Bergi Jan 30 '20 at 07:30
-
for `abstraction/encapsulation`. – AZ_ Jan 30 '20 at 07:31
1 Answers
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