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.}
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.