- As the array (2001, 1999, 2000 and 2002) grows by 4 years
- The array is displayed on the screen, featuring the same 4 years
- It's determined that the highest year is 2002
- 2002 is then removed from the array
- The array is again shown on the screen with all 4 years still present
- Surprisingly, it turns out that after deleting 2002, the maximum year is now calculated as 2001
What seems to be the issue?
const output = document.getElementById('output');
function handleYears() {
let years = [];
let addYear = function(newYear) {
years.push(newYear);
}
let deleteYear = function(yearToDelete) {
years = years.filter(item => item !== yearToDelete)
}
let calculateMaxYear = function() {
return Math.max(...years);
}
return {
years: years,
addYear: addYear,
deleteYear: deleteYear,
calculateMaxYear: calculateMaxYear
}
}
let newHandleYears = handleYears();
newHandleYears.addYear(2001);
newHandleYears.addYear(1999);
newHandleYears.addYear(2000);
newHandleYears.addYear(2002);
output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
output.innerHTML += `<p>The item "${newHandleYears.years[newHandleYears.years.length - 1]}" will now be deleted from the "years" array.</p>`;
newHandleYears.deleteYear(2002);
output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
body {padding: 0.5rem 1rem;}
<div id="output"></div>