Accessing calculated property in javascript object

Viewed 70

Why does the console print undefined when I access age property directly. I have to print calcAge function first in order to get the value.

const Osama = {
    firstName: 'osama',
    lastName: 'Shaikh',
    birthyear: 1999,
    job: 'developer',
    friends: ['michael', 'peter', 'steven'],
    haslicense: true,
    calcAge: function () {
        this.age = 2021 - this.birthyear;
        return this.age;
    },

};
console.log(Osama.age);
2 Answers

That object doesn’t have an age property to begin with.

You only assign it when you run the calcAge method.

It seems like you're looking to assign a getter for the age property.

const Osama = {
  birthyear: 1999,

  get age() {
    console.log('in getter');
    return 2021 - this.birthyear;
  },
};

console.log(Osama.age); // in getter, 22
console.log(Osama.age); // in getter, 22

Or, to calculate the age only on first access and replace it with a static property you can use a self-overwriting getter.

const Osama = {
  birthyear: 1999,
  
  get age() {
    console.log('in getter');
    delete this.age;

    return (this.age = 2021 - this.birthyear);
  },
};

console.log(Osama.age); // in getter, 22
console.log(Osama.age); // 22

Related