Understanding Getters and Setters in JavaScript

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.

javascript
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.

javascript
1console.log(user.fullName);
text
1John Doe

If you try to access them as a method, JavaScript will return an error.

javascript
1console.log(user.fullName());

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉