JavaScript program to find years with first January Sunday

Introduction :

In this JavaScript tutorial, we will learn how to find out if the first January is Sunday or not between two years. This is a beginner level JavaScript problem. You will learn how to check if a day is Sunday or not using Date class in JavaScript and how to use a for loop.

JavaScript getDay() method :

getDay() method is used to get the day of a week in JavaScript date. For example :

let d = new Date();
console.log(d.getDay());

If you run it, it will return one number indicating the day of the week. It is in range 0 to 6. 0 is for Sunday and 6 is for Saturday.

So, we will create one Date object using the constructor Date(year, month, date) and check if it is Sunday or not.

JavaScript program :

let startYear = 2000;
let endYear = 2050;

for(let currentYear = startYear; currentYear <= endYear; currentYear++){
    if(new Date(currentYear, 0, 1).getDay() === 0){
        console.log(currentYear);
    }
}

It will print :

2006
2012
2017
2023
2034
2040
2045

All these years have Sunday on 1st January.

JavaScript first january sunday