Range of Years in JavaScript for a select box
JavaScript does have a Range object, but it refers to an arbitrary portion of the DOM and is not supported in IE 6/7.
If you want, you can simplify your function to this, but it's all the same really.
this.years = function(startYear) {
var currentYear = new Date().getFullYear(), years = [];
startYear = startYear || 1980;
while ( startYear <= currentYear ) {
years.push(startYear++);
}
return years;
}
console.log( this.years(2019-20));
Use Array.fill() if you're transpiling or not worried about IE users.
const now = new Date().getUTCFullYear();
const years = Array(now - (now - 20)).fill('').map((v, idx) => now - idx);
// (20) [2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000]
TypeScript
get years() {
const now = new Date().getUTCFullYear();
return Array(now - (now - 20)).fill('').map((v, idx) => now - idx) as Array<number>;
}
Use Array.from
const currentYear = (new Date()).getFullYear();
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
console.log(range(currentYear, currentYear - 50, -1));
// [2019, 2018, 2017, 2016, ..., 1969]