I am learning Javascript, and I am coming across a couple of hiccups. This is my first post here, please help me understand:
- Why does a number (ex: 2024), subtracted by my javascript object property: 'this.birthYear' (ex: 1995, clearly a number) return Not a Number (NaN)? Could this possibly be a parsing error to my browser's console?
- And, if this is my error, what would I need to change in my code to make 2024 - 1995 = 29?
Here is my code:
const penguin = {
firstName: 'Zachary',
birthYear: 1995,
job: 'Developer',
friends: ['Michael', 'Joe', 'Evan'],
hasDriversLicense: true,
// methods
calcAge: function () {
this.age = 2024 - this.birthyear;
return this.age;
},
getSummary: function () {
this.hasDriversLicense ? this.getSummary = 'a' : this.getSummary = 'no';
return this.getSummary;
}
};
penguin.calcAge();
penguin.getSummary();
console.log(penguin.age); // why NaN ???
console.log(penguin.getSummary);
// summary
console.log(`${penguin.firstName} is a ${penguin.age} year-old ${penguin.job}, and he has ${penguin.getSummary} Driver's License.`);
Refer to screenshot for my output example.
Thank you in advance.
I have tried logging to my browser console console.log(penguin.age), which outputs NaN (But, if hard-coding a 1995 number, I get my expected result: 29).
Check the spelling of this.birthyear within your calcAge function, you want it to be this.birthYear.