I've been playing with JS and I'm trying to assign a new variable inside an object method but I keep getting hit with undefined in the console.
This is the object I created:
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYEar: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
calcAge: function () {
this.age = 2021 - this.birthYEar;
return this.age; //We don't actually need to return anything here actually, because we already said that age = calculation.
}
But when I try to log rodrigo.age it returns undefined. Could someone walk me through this? I'm not understanding what I'm doing wrong.
Your object doesn't initially have an age property assigned to it. To be able to access age you need to execute the calcAge function via rodrigo.calcAge() first.
If you want rodrigo.age to return something, you'll have to define that property. But since you defined calcAge instead, and never call that method, there is no age property (yet).
One solution is to replace calcAge with a getter function named age. The advantage is then that you can read rogrigo.age and implicitly invoke that function:
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYear: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
get age() {
return new Date().getFullYear() - this.birthYear;
}
}
console.log(rodrigo.age);
Side note: the calculation of age is a bit more complex than this -- you need to know someone's full birthdate and compare it with the current month and date to see whether it already passed.
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYEar: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
calcAge: function () {
this.age = 2021 - this.birthYEar;
console.log(this.age);
return this.age;
}
}
rodrigo.calcAge();