Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

73
Views
Accessing calculated property in javascript object

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);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

You only assign it when you run the calcAge method.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!