Design comparison
Solution retrospective
Write your Review. to improve this in this code JavaScript some if am enter greater then current date so this code give result in negative value help me to correct this 🥰😊😎🥰
Community feedback
- @AyoubrabiaePosted about 1 year ago
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.
0@Siddarth-abcsPosted about 1 year ago@Ayoubrabiae Sure am correct this problem and organized code thank you for finding my mistake 😊
1
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord