I don't understand getter

what is the get keyword use ?

const person = {
_firstName: ‘John’,
_lastName: ‘Doe’,
get fullName() {
if (this._firstName && this._lastName){
return ${this._firstName} ${this._lastName} ;
} else {
return ‘Missing a first name or a last name.’;
}
}
}
// To call the getter method:
person.fullName; // ‘John Doe’

is there any different if we omit the let keyword

Please post a link to the exercise page.

What have you learned from the lesson narrative?

https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/getters
Getters are methods that get and return the internal properties of an object.”
I don’t really understand that sentence

so the get keyword is used the same as calling the property but limits it to only getting the information, they can’t change anything. In the example you gave, the get keyword allows you to get the first and last name, but doesn’t allow you to change the first and last name. This doesn’t seem important in small code like this, but when you have millions of lines of code it’s important to ensure that data isn’t changed by accident.

the set method is the same except that it’s used to change the data (e.g. it would allow you to change first name and last name) while also verifying that the new name input is actually a name and not, for example, a number.

3 Likes