Function inside object won't work

Any idea why this won’t work? when i put it in the console I get undefined and don’t understand why. everything else works but trying to call the age.

const ethan = {
    firstName: 'Ethan',
    lastName: 'Reynolds',
    job: 'prison Gaurd',
    birthYear: 1995,
    friends: ['john', 'peter', 'james'],
    hasDriversLicense: true,
    calcAge: function () {
        this.age = 2021 - this.birthYear;
        return this.age;
    }
};
console.log(ethan.age);

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

It doesn’t look like you called the calcAge function. Until you do so, the age should be undefined.

Thank you, this solved it. Can you briefly explain why I had to do that or how it works?

When you first created the object, you did not define the age. So you need to call the function that defines the age before you can use that property. The function won’t run unless it’s called.

1 Like

Thank you Jeremy, much help!

1 Like