I'm a bit confused with objects in JavaScript...
I wrote an object:
const gix = {
firstName: "John",
lastName: "Johnson",
yearOfBirth: 2000,
profession: "IT",
friends: ["Mark", "Luke", "John"],
driversLicence: true,
age: function () {
this.calcAge = 2022 - this.yearOfBirth;
return this.calcAge;
},
};
gix.age();
console.log(gix);
Why is the console log of the whole object not showing the calculated value but is showing age: f()
Considering your use-case, you could replace the method with a getter, which gets evaluted each time the object is referenced:
const gix = {
firstName: "John",
lastName: "Johnson",
yearOfBirth: 2000,
profession: "IT",
friends: ["Mark", "Luke", "John"],
driversLicence: true,
get age() {
return 2022 - this.yearOfBirth;
},
};
You would either want to capture the return value of the function or call it so:
console.log(gix.age());
Think of age as a pointer to the function...
When you're console logging a function it wont execute it, It will just show the contents of the function, IF you need to see the value then you need to call the function and log the output
console.log(gix.age());