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
}

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.

Write a Comment

Comment