@Ayoubrabiae
Posted
Hi Siddarth,
I've reviewed your JavaScript code, and I see that there are several improvements you can make. To enhance your code, you should organize it into functions, each responsible for a specific task. For instance:
- Create a function to validate the year:
const validateYear = (year) => {
const currentYear = new Date().getFullYear();
if (year >= (currentYear - 200) && year <= currentYear && year) {
return true;
}
return false;
};
- Implement a function to calculate the age:
const calculateAge = (year, month, day) => {
const today = new Date();
let age = today.getFullYear() - year;
const monthDiff = (today.getMonth() + 1) - month;
const dayDiff = today.getDate() - day;
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
age--;
}
return age;
};
- Create a function to add the day, month, and year to the elements when you click the button:
const onClickHandler = () => {
const yearInput = document.querySelector("[name='year']");
const monthInput = document.querySelector("[name='month']");
const dayInput = document.querySelector("[name='day']");
const resultValue = document.querySelector('.calculator--resultValue');
if (!isDateValid(dayInput, monthInput, yearInput)) {
return;
}
resultValue.textContent = calculateAge(yearInput.value, monthInput.value, dayInput.value);
};
By organizing your code this way, it will become more readable and easier to enhance and debug. If you need further assistance or clarification, feel free to ask.
@Siddarth-abcs
Posted
@Ayoubrabiae Sure am correct this problem and organized code thank you for finding my mistake 😊
@Ayoubrabiae
Posted
@Siddarth-abcs Welcome any time!