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

104
Views
Declaring a new variable inside Object

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

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!