Why age is showing undefined

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

    calcAge: function () {
        this.age = 2037 - this.birthYeah;
        return this.age;


I’ve edited your code 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 (').

There is no age key.
You have a calcAge key though.
I would use that to get the age

Yeah, it’s odd. As Jessica says, you don’t have a key for “age”. But you do add it in the calcAge method. Which also returns it. Which is it doing? Calculating it and adding it to the object? Or is it calculating it and returning it? I don’t think it should do both.

I mean, it would work like this:


As Jessica points out, it would also work like this:


The problem is that initially there is no “age” prop, until after calcAge is run.

Another option, if you want it to be dynamic (calculate it each time it is called) but access it like a property, you could use a getter.

So, you get rid of calcAge and add this to your object:

    get age() {
      return 2037 - this.birthYeah

Then you can access it with:


With a getter, you write it like a method (function), but you access it like it is a property - JS knows to call the function. In this case, “age” is not stored on the object but it calculated every time that “property” is accessed.

Thank you soo much your answer was really helpfull

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.