We did not explicitly mention this, but we've been discussing a concept called object-oriented programming. It is a programming paradigm where we use objects to create everything. Under this paradigm, our program will be divided into reusable pieces in the form of objects.
However, it is not yet time for us to discuss this concept in detail, because there are many things we have to talk about first. For this lesson, we'll be focusing on the getters and setters. They are special properties inside of an object, which are in charge of getting and setting a property value.
Getters
Getters are created with the keyword get
, and they are defined like methods.
1let user = {
2 firstName: "John",
3 lastName: "Doe",
4 role: "Visitor",
5 get fullName() {
6 return `${this.firstName} ${this.lastName}`;
7 },
8};
However, to external programs, they act like properties, and should be accessed like properties.
1console.log(user.fullName);
1John Doe
If you try to access them as a method, JavaScript will return an error.
1console.log(user.fullName());