Exercise 10: Calculate Age from Date of Birth

Problem Statement

Create a function `calculateAge(dob)` that calculates age from date of birth. Example: calculateAge("1990-05-15") → 34 (assuming current year is 2024)

Sample Output:

calculateAge("1990-05-15") => 34 (if current date is 2024-06-01)
calculateAge("2000-12-25") => 23 (if current date is 2024-01-01)

Solution

const calculateAge = (dob) => {
  const birth = new Date(dob);
  if (isNaN(birth.getTime())) return null;
  const today = new Date();
  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) age--;
  return age;
};

Explanation

Overall Goal:

  • Date of birth se accurate age calculate karna.
  • Birthday abhi nahi aaya ho to age kam karna.

Line 1: Function header

  • const calculateAge = (dob) => {

Line 2: Parse date

  • const birth = new Date(dob);
  • String date ko Date object me convert.

Line 3: Validate date

  • if (isNaN(birth.getTime())) return null;
  • Invalid date ho to null return.

Line 4: Current date

  • const today = new Date();

Line 5: Year difference

  • let age = today.getFullYear() - birth.getFullYear();
  • Basic age calculation.

Line 6: Month difference

  • const monthDiff = today.getMonth() - birth.getMonth();

Line 7: Adjust if birthday not passed

  • if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) age--;
  • Agar current month birthday month se pehle hai → age--.
  • Agar same month hai lekin date abhi nahi aayi → age--.

Real world:

  • User registration: age verification.
  • E-commerce: age-restricted products.
  • Banking: account opening age requirements.