Home > Enterprise >  Accessing calculated property in javascript object
Accessing calculated property in javascript object

Time:12-05

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);

CodePudding user response:

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

You only assign it when you run the calcAge method.

CodePudding user response:

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
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related