Simple Age Calculator
Today I learned how to build a simple age calculator in JavaScript, including converting user input into numbers and handling invalid input safely.
Today I learned how to create a simple age calculator in JavaScript. The challenge looked easy at first, but it introduced an important concept: handling user input correctly before performing any calculations.
The goal was to ask for a birth year and calculate the user's age automatically.
const birthYear = prompt("Enter your birth year: ");
const birth = parseInt(birthYear);
const currentYear = new Date().getFullYear();
const age = currentYear - birth;
console.log(`You are ${age} years old.`);The output would look something like this:
My First Mistake
At first, I accidentally mixed browser input methods with Node.js input methods. I tried writing something like this:
const readline = prompt();
const birthYear = readline.question("Enter your birth year: ");This doesn't work because prompt() belongs to the browser, while readline.question() belongs to Node.js. They are different environments and cannot be combined together.
Calculating Age
After fixing the input logic, I used the current year from JavaScript's Date object and subtracted the birth year.
const birthYear = prompt("Enter your birth year: ");
const birth = parseInt(birthYear);
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.`);The result becomes more informative and easier to understand:
The current year is 2025.
That means you're 20 years old.
Next year you'll be 21 years old.
Why do we use parseInt()?
I was curious why this line was necessary:
const birth = parseInt(birthYear);The value returned by prompt() is always a string. Since age calculation requires numbers, we need to convert the string into a numeric value first.
Without conversion, JavaScript may produce unexpected results when performing calculations.
Input Validation
A calculator should not only work for valid input, but also handle unexpected cases gracefully.
if (birth > currentYear) {
console.log("Are you from the future?");
}if (isNaN(birth)) {
console.log("Invalid input. Please enter a valid birth year.");
}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}.
The current year is ${currentYear}.
That means you're ${age} years old.
Next year you'll be ${nextYear} years old.`);
}