JavaScript program to find all years in a range with first January Monday

JavaScript program to find all years in a range with first January Monday :

In this JavaScript program, we will learn how to find all years in a range with first January as Monday. With this program, you will learn how to use a loop in JavaScript and how to check the current day using Date constructor.

You can change the program to find out if a day is Tuesday or any other day.

JavaScript Date object to find a day :

JavaScript Date object can be created in a different way. One way is to pass the year, month and day to the constructor and it creates the date object. We can use getDay() method to get the current day on this object.

Now, our problem is to find all years in a range with first January as Monday. To solve it, we can start one loop that will iterate through these years one by one. For each iteration, we will create one Date object with year as the current year, month as the January and day as 1 i.e. first January for that year. We will use getDay() method to check if it returns 1 or not. 0 is for Sunday, 1 is for Monday etc.

Let’s code :

Using a for loop :

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

In this program, one for loop runs from 2014 to 2050. For each value, it creates one Date object using that value as the year, month as January or 0 and day as 1. We are using one if statement to check if the day for that Date is 1 or not i.e. Monday or not. If it is Monday, we are printing the value of that year on console.

Output :

If you execute the program, it will print the below output :

2018
2024
2029
2035
2046

JavaScript find years range first january monday