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

March 14, 2020

function generateYearsBetween(startYear = 2000, endYear) {
  const endDate = endYear || new Date().getFullYear();
  let years = [];

  for (var i = startYear; i <= endDate; i++) {
    years.push(startYear);
    startYear++;
  }
  return years;
}

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

const yearsArray = generateYearsBetween(2007, 2014);

This will generate the following array of years:

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

While Loop

You can accomplish the same thing using a while loop:

function generateYearsBetween(startYear = 2000, endYear) {
  const endDate = endYear || new Date().getFullYear();
  let years = [];

  while (startYear <= endDate) {
    years.push(startYear);
    startYear++;
  }
  return years;
}