How to Generate An Array of Years Between Two Dates In Javascript

March 14, 2020

javascript
js
1.function generateYearsBetween(startYear = 2000, endYear) {
2. const endDate = endYear || new Date().getFullYear();
3. let years = [];
4.
5. for (var i = startYear; i <= endDate; i++) {
6. years.push(startYear);
7. startYear++;
8. }
9. return years;
10.}

This generates an array of years between the startYear and endYear. startYear defaults to 2000 and endYear defaults to the current year using the Date() function.

Usage

js
1.const yearsArray = generateYearsBetween(2007, 2014);

This will generate the following array of years:

js
1.[2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014];

While Loop

You can accomplish the same thing using a while loop:

js
1.function generateYearsBetween(startYear = 2000, endYear) {
2. const endDate = endYear || new Date().getFullYear();
3. let years = [];
4.
5. while (startYear <= endDate) {
6. years.push(startYear);
7. startYear++;
8. }
9. return years;
10.}