Code Challenges: JavaScript fundamentals howOld()

2020-07-07T13:32:00Z

I’m just looking for some feedback on the structure of the code, if there is a more efficient way of achieving the same goal, and any bad habits that you may see.

First time posting.

Thank You

(https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/code-challenge-javascript-fundamentals/lessons/javascript-fundamentals-code-challenge/exercises/how-old)

// Write your function here:
const howOld = (age, year) => {
let currentYear = new Date().getFullYear();
//console.log(currentYear);
let yearDiff = year - currentYear;
//console.log(yearDiff);
let newAge = age + yearDiff;
//console.log(newAge);
let yearBorn = currentYear - age;
//console.log(yearBorn);
let yearsBefore = Math.abs(yearBorn - year);
//console.log(yearsBefore);
if (newAge < 0) {
return The year ${year} was ${yearsBefore} years before you were born;
} else if (newAge < age) {
return You were ${newAge} in the year ${year};
} else {
return You will be ${newAge} in the year ${year};
}
}

console.log(howOld(29, 1960));
console.log(howOld(29, 2045));
console.log(howOld(29, 2018));

// Once your function is written, write function calls to test your code!

Hi, thanks for sharing!

If you get a moment, highlight your code and format it with </> especially if you want feedback on things like readability :slight_smile:

The only thing I would suggest is consider your testing logs at the end. Even if the code sample works here, in principle, I would try to use a range of numbers that might “break” my code. (Like, can it handle small, large, even, negative numbers? What happens if you put a negative year?) It’s not “wrong” the way you’re doing it but it can be something to look out for in more complicated code later.

1 Like

For future reference: How do I format code in my posts?