Sometimes, we want to loop through a date range with JavaScript.
In this article, we’ll look at how to loop through a date range with JavaScript.
How to loop through a date range with JavaScript?
To loop through a date range with JavaScript, we can use a while loop.
For instance, we write
let start = new Date("02/05/2022");
let end = new Date("02/10/2022");
let loop = new Date(start);
while (loop <= end) {
console.log(loop);
const newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
to create the start and end dates.
Then we create the loop date from the start date that we use as the loop variable.
Next, we add a while loop that runs while loop is less than or equal to end.
In it, we log the loop variable.
Then we call setDate with loop.getDate() + 1 to create newDate.
And then we update loop to newDate with
loop = new Date(newDate)
Conclusion
To loop through a date range with JavaScript, we can use a while loop.