EN
JavaScript - create object with getter
0 points
In this article, we would like to show you how to create object with getter in JavaScript.
Quick solution:
xxxxxxxxxx
1
const user = {
2
id: "1",
3
username: "Tom",
4
country: "USA",
5
get name() {
6
return this.username;
7
}
8
};
9
10
console.log(user.name); // Tom
In this example, we use the get
keyword to create an object with a getter that returns last number from the numbers
array which is inside the object.
xxxxxxxxxx
1
const object = {
2
numbers: [1, 2, 3],
3
get last() {
4
if (this.numbers.length > 0) {
5
return this.numbers[this.numbers.length - 1];
6
}
7
return undefined;
8
},
9
};
10
11
console.log(object.last); // 3
Output:
xxxxxxxxxx
1
3