-1

I was practicing creating an object in JS and created the following object:

const jonas = {
    firstName: 'Jonas',
    lastName: 'Schmedtmann',
    birthYear: 1991,
    job: 'teacher',
    friends: ['Michael', 'Peter', 'Steven'],
    hasDriversLicense: false,

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

A strange thing happen when I want to print the output of the function calcAge with the following code:

console.log(jonas.age);

The browser outputs "undefined" for the console.log() command.

Can anyone tell me where I got it wrong?

Thanks!

2
  • 1
    have you executed jonas.calcAge() before the console.log Commented Mar 10, 2021 at 5:52
  • @lastr2d2 Thanks. I have solved this with your advice. Commented Mar 10, 2021 at 9:45

2 Answers 2

1
const jonas = {
    firstName: 'Jonas',
    lastName: 'Schmedtmann',
    birthYear: 1991,
    job: 'teacher',
    friends: ['Michael', 'Peter', 'Steven'],
    hasDriversLicense: false,

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

here calcAge is a function declaration that will add age property to the object by accessing the birthYear property of the same object. Everything sounds good but this all going to happen only if the function is called/executed.

function declaration and function call/execution is two different thing. so the console output is undefined as the function is never called

so need to call the function

jonas.calcAge()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is solved. I learnt a lot!
0

console.log(jonas.calcAge()); will give you the value of age

or

jonas.age = jonas.calcAge();

then

console.log(jonas.age);

1 Comment

Thank you. My problem is solved. Learnt a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.