Code Challenges: JavaScript fundamentals howOld()


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


// Write your function here:
const howOld = (age, year) => {
let currentYear = new Date().getFullYear();
let yearDiff = year - currentYear;
let newAge = age + yearDiff;
let yearBorn = currentYear - age;
let yearsBefore = Math.abs(yearBorn - year);
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?