Find how many Sundays fell on the first of the month for a given year using JavaScript — Programming Interview Questions.

Mansi Manhas
2 min readNov 30, 2021

--

Write a program to determine how many Sundays fell on the first of the month for a given year.

We’ll go through the first of every month in a year and check if it’s a Sunday. We’ll use a counter and keep incrementing the counter whenever we find a Sunday.

Implementation using JavaScript:

We first need to find out the day of any given date in JavaScript. This is because JavaScript uses a built-in Date object that implements getDay — that for a specific date returns the day of the week.

Example:

const mydate = new Date('November 30, 2021 23:15:30');
const day1 = mydate.getDay();
console.log(day1);OUTPUT: 2

It represents Sunday to Saturday, starting from 0 till 6, i.e. it is a Sunday when getDay returns 0.

Thus, we’ll just iterate over 1st of all the months in the given year and store the number of Sundays in a counter variable.

function numSundaysOnFirst(year) {
let sundays = 0;

for (let month = 1; month <= 12; month++) {
if (new Date(year, month, 1).getDay() === 0) {
sundays++;
}
}
return sundays;
}

That’s all.
You can also practice a slight variation of this problem on the HackerRank platform here.

Reference to other programming questions —
Find Maximum Profit in Job Scheduling
Convery Binary Number in a Linked List to Integer
Find Perfect, Deficient, and Abundant Numbers

--

--

Mansi Manhas

Tech enthusiast, wanderlust, coffee addict! ☕️ Senior Software Engineer, enhancing product experiences. https://www.linkedin.com/in/mansimanhas/