howOld() - code logging NaN

Hello everyone, I’m stuck and need help! The following code is bringing back "You were NaN in the year 2050. It should be returning “You will be 67 in the year 2050”. Can anyone please tell me why it is doing this?
A link to the exercise is as follows: http://codecademy.com/paths-redirect/5b32457b646caa5007c30975/dfbca5c79d1142fc8dcdc09c064f00b6/exercises/how-old

const howOld = (age, year) => {

const yearDifference = year - theCurrentYear

var theCurrentYear = 2021

const newAge = age + yearDifference

if (newAge < 0) {
console.log('The year'  + year + ' was ' + -newAge + ' years before you were born');
} 
else if (newAge > age) {
   console.log('You will be ' + newAge + ' in the year ' + year);
} 
else {
  console.log('You were ' + newAge + ' in the year ' + year);
}
}

howOld(37, 2050)

`theCurrentYear is an undefined variable. So the subtraction (year - theCurrentYear) gives NaN (not a number)

then you have the same problem here:

const newAge = age + yearDifference

given yearDifference is now NaN. so the sum result in NaN again

Thank you! I changed it to new Date.getFullYear() and it worked. However, I don’t understand why it didn’t work when I defined it as 2021 as follows:

var theCurrentYear = 2021

seems you made an edit to your original topic.

well, looking at the code:

const yearDifference = year - theCurrentYear

var theCurrentYear = 2021

you declare the variable after using the (undefined) variable

variables need to be declared before you use them, not after

That’s very helpful! Thank you!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.