Simple Age Calculator
Today's challenge really made my brain curl 😅 We were asked to create a JavaScript program that calculates someone's age based on their birth year. Sounds simple, but when I actually started coding, there were quite a few traps.
Challenge Description
Create a program that:
- Asks the user to enter their birth year
- Calculates their current age
- Displays a message like this:
You were born in 2005.
The current year is 2025.
That means you're 20 years old 🎉
Next year you'll be 21 years old.
Thought Process (and Small Mistakes 😅)
At first I thought the input could be written like this:
const readline = prompt();
const birthYear = readline.question("Enter your birth year: ");
Turns out... WRONG!
I forgot that prompt()
only works in browsers, while readline.question(...)
is part of Node.js's readline
module - and you can't mix them.
Luckily I still understood the logic. After some more tinkering (and asking ChatGPT too 🤭), I finally got the correct version:
Browser Version Solution
const birthYear = prompt("Enter your birth year: ");
const birth = parseInt(birthYear); // convert input string to number
const currentYear = new Date().getFullYear();
const age = currentYear - birth;
const nextYear = age + 1;
console.log(`You were born in ${birthYear}. The current year is ${currentYear}. That means you're ${age} years old 🎉 Next year you'll be ${nextYear} years old.`);
Why parseInt()?
Because input from prompt()
is always a string. If we want to calculate age, we need to convert it to a number first. That's why we need parseInt()
or we could also use Number()
.
Bonus Challenge: Validation & Edge Cases
The bonus challenge was fun too: we were asked to add additional logic so the program could handle weird cases, like...
Case 1: User Enters Year Greater Than Current Year
if (birth > currentYear) {
console.log("Are you from the future? 🛸");
}
Case 2: Invalid Input (Letters, empty, etc)
if (isNaN(birth)) {
console.log("Invalid input. Please enter a valid birth year.");
}
Bonus Tip: Use \n
for cleaner output
In JavaScript console, \n
works like <br>
in HTML. So we can format the output to be more readable.
Final Code
const birthYear = prompt("Enter your birth year: ");
const birth = parseInt(birthYear);
const currentYear = new Date().getFullYear();
const age = currentYear - birth;
const nextYear = age + 1;
if (isNaN(birth)) {
console.log("Invalid input. Please enter a valid birth year.");
} else if (birth > currentYear) {
console.log("Are you from the future? 🛸");
} else {
console.log(`You were born in ${birthYear}.\nThe current year is ${currentYear}.\nThat means you're ${age} years old 🎉\nNext year you'll be ${nextYear} years old.`);
}