Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my Javascript method return NaN when two number types are calculated?

I am learning Javascript, and I am coming across a couple of hiccups. This is my first post here, please help me understand:

  1. 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?
  2. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

>Solution :

Check the spelling of this.birthyear within your calcAge function, you want it to be this.birthYear.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading