skip to Main Content
const rajat = {
  FirstName: "Rajat",
  middleName: "Kumar",
  lastName: "sahoo",
  birthYear: 1998,
  location: "Bhubaneswar",
  job: "Programmer",
  friends: ["Michel", "Jack", "James", "Juile"],

  calcAge: function () {
    this.Age = 2023 - this.birthYear;  // `here if i creat the age object it give undefine output`
    return this.Age;                   // `But when i normally call the function it works properly`
  },
};

console.log(rajat.Age);

I am just trying to calculate age using this method by creating an object but whenever i am trying to create the age object the output that I get is undefined why???

2

Answers


  1. Consider making the Age a getter property:

    const rajat = {
      FirstName: "Rajat",
      middleName: "Kumar",
      lastName: "sahoo",
      birthYear: 1998,
      location: "Bhubaneswar",
      job: "Programmer",
      friends: ["Michel", "Jack", "James", "Juile"],
      get Age() {
        return 2023 - this.birthYear;
      }
    };
    
    console.log(rajat.Age);
    Login or Signup to reply.
  2. You didn’t call rajat.Age() before printing it. Calling a function is like saying that you are going to use that function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search