Reputation: 173
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!
Upvotes: -1
Views: 75
Reputation: 87
console.log(jonas.calcAge());
will give you the value of age
or
jonas.age = jonas.calcAge();
then
console.log(jonas.age);
Upvotes: 0
Reputation: 2713
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()
Upvotes: 1