Generate an array of years in JavaScript

in Code Write a comment

In this tutorial, youโ€™ll learn how to create a list or an array of years in JavaScript. You can copy this snippet and use it in your projects e.g. to create form fields.

I use it quite a lot in my projects. For example, I once needed a drop-down field that would have a list of 10 most recent years (present โ€“ 10).

2019,2018,2017,2016,2015,2014,2013,2012,2011,2010

The following snippet does exactly what I needed.

function generateArrayOfYears() {
  var max = new Date().getFullYear()
  var min = max - 9
  var years = []

  for (var i = max; i >= min; i--) {
    years.push(i)
  }
  return years
}

Hi, I'm Renat ๐Ÿ‘‹

โžœ  


generateArrayOfYears() function will create an array of 10 most recent years no matter what year it is.

It uses a JavaScript Date() object to get the current year.

Thereโ€™re a lot of things you can now do with this array. You can create an utility in Vue.js, Angular or React to quickly generate years.

yearFoundedOptions: utils.generateArrayOfYears()

Alternatively, you can output it in your HTML template as a string.

HTML:

<div id="years"></div>

JavaScript:

function generateArrayOfYears() {
  var max = new Date().getFullYear()
  var min = max - 9
  var years = []

  for (var i = max; i >= min; i--) {
    years.push(i)
  }
  return years
}

var years = generateArrayOfYears().toString();

document.getElementById('years').innerHTML = years;

Result:

2019,2018,2017,2016,2015,2014,2013,2012,2011,2010

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
๐Ÿ‘‰renatello.com/javascript-array-of-years

PS: Make sure you check other JavaScript tutorials, e.g. how to create an array of numbers in JavaScript.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

5 Comments

  1. Perfect worked for me. I wanted to fetch next 5 years to bind it to the dropdown in Angular. So edited few lines. Kudos to you.

  2. The same logic can be written in two lines of javascript.

    “`
    const year = new Date().getFullYear();
    const years = Array.from(new Array(10), (v, idx) => year + idx);
    “`
    Then if you were using react, you might want to return these years formatted as “ in a select list with JSX like this:

    “`
    const yearOpts = years.map((year) => {
    return (

    {year}

    );
    });
    “`