'how can i get age from this keyword?

const meDetails = {
    firstName: 'arman',
    lastName: 'soltani',
    birthday: 1991,
    hasDriverLicense: true,

    calcAge: function () {
        this.age = 2037 - this.birthday;
        return this.age;
    }
};

console.log(meDetails.age);

why the age is not defined??



Solution 1:[1]

the variable of named 'age' is not initialized before calling calcAge.

at first you should call calcAge to init meDetailes.age variable at runtime then meDetails.age is valued and you can use it

Solution 2:[2]

You need to call calcAge() first to set the age property

meDetails.calcAge();
console.log(meDetails.age);

But you probably want a getter for age.

const meDetails = {
    firstName: 'arman',
    lastName: 'soltani',
    birthday: 1991,
    hasDriverLicense: true,
    
    get age() {
      return 2037 - this.birthday;
    }
};

console.log(meDetails.age);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad
Solution 2 Hao Wu