Emmanuel Akinfulubi

JavaScriptDate

Build a calendar grid for a month in JavaScript

Advanced · 4 min read

Booking sites, event pages and date pickers all show a month as a grid: seven columns for the days of the week, and a row for each week. Before you can draw that grid, you need the data behind it. Which days go in which row, and how many empty boxes come before the 1st?

In this tutorial you will write monthGrid(year, month, firstDayOfWeek). It returns an array of weeks, each with seven cells. A cell holds a day number, or null when it belongs to another month. It works with weeks that start on Monday or on Sunday. You need to know getDay() (0 for Sunday to 6 for Saturday), that months count from 0, and how loops and arrays work.

What the grid looks like

Here is January 2026 with Monday first. The 1st is a Thursday, so three boxes come before it:

Output

Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

As data, that is five arrays of seven cells. The first row is [null, null, null, 1, 2, 3, 4].

The plan

  1. Work out how many blank cells come before the 1st.
  2. Add the days of the month.
  3. Add blanks at the end until the total is a multiple of 7.
  4. Cut the long list into rows of 7.

Here is the exercise. Try it on your own first if you like, then read on and we will build it step by step.

57 A month laid out as a calendar grid

hard

Build the rows of a month calendar: an array of weeks, each with seven cells, null where the cell belongs to another month. Support Monday-first and Sunday-first.

Stuck? Three hints, smallest first
  1. 1. How many blanks come first is the modular gap between the 1st’s weekday and the first day of the week.
  2. 2. Pad the end until the total number of cells is a multiple of seven.
  3. 3. Then slice the flat list into rows of seven.

Step 1: the month's length and its first weekday

Step 1

const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
console.log(daysInMonth(2026, 0));          // 31
console.log(new Date(2026, 0, 1).getDay()); // 4

Day 0 of the next month is the last day of this one, so daysInMonth gives 31 for January. The 1st is weekday 4, a Thursday.

Step 2: count the leading blanks

The number of blanks is how far the 1st's weekday is from the first day of the week. With Monday (1) first, Thursday (4) is 3 days in:

Step 2

const lead = (firstWeekday, firstDayOfWeek) => (firstWeekday - firstDayOfWeek + 7) % 7;
console.log(lead(4, 1)); // 3
console.log(lead(4, 0)); // 4
console.log(lead(0, 1)); // 6

With Sunday (0) first, there are 4 blanks. And if the 1st is a Sunday but weeks start on Monday, the 1st goes in the last column, after 6 blanks.

The + 7 matters. Without it, 0 - 1 would give -1, and in JavaScript -1 % 7 is -1, not 6. Adding 7 keeps the answer between 0 and 6 without changing the weekday.

Step 3: blanks, then the days

Step 3

const cells = [];
for (let i = 0; i < 3; i++) cells.push(null);
for (let day = 1; day <= 31; day++) cells.push(day);
console.log(cells.length); // 34

3 blanks plus 31 days make 34 cells. That isn't a multiple of 7, so the last row is short.

Step 4: pad the end

Step 4

while (cells.length % 7 !== 0) cells.push(null);
console.log(cells.length); // 35

cells.length % 7 is the remainder after dividing by 7. While it isn't 0, add another blank. One blank brings it to 35, which is exactly five rows.

Step 5: cut into rows of seven

Step 5

const weeks = [];
for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
console.log(weeks.length); // 5
console.log(JSON.stringify(weeks[0])); // [null,null,null,1,2,3,4]
console.log(JSON.stringify(weeks[4])); // [26,27,28,29,30,31,null]

The loop jumps 7 at a time. slice(i, i + 7) copies the 7 cells starting at i into a new array, which becomes one row.

Step 6: put it in one function

Step 6

function monthGrid(year, month, firstDayOfWeek) {
  const firstWeekday = new Date(year, month, 1).getDay();
  const lead = (firstWeekday - firstDayOfWeek + 7) % 7;
  const cells = [];
  for (let i = 0; i < lead; i++) cells.push(null);
  for (let day = 1; day <= daysInMonth(year, month); day++) cells.push(day);
  while (cells.length % 7 !== 0) cells.push(null);
  const weeks = [];
  for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
  return weeks;
}
console.log(JSON.stringify(monthGrid(2026, 0, 0)[0])); // [null,null,null,null,1,2,3]
console.log(JSON.stringify(monthGrid(2026, 1, 1)[0])); // [null,null,null,null,null,null,1]

With Sunday first, January starts after four blanks. February 2026 starts on a Sunday, so with Monday first the 1st sits alone at the end of the first row.

Step 7: the wrong turn, assuming five rows

It is tempting to always draw five rows. Count the rows for a few months:

Step 7

console.log(monthGrid(2026, 0, 1).length); // 5
console.log(monthGrid(2026, 1, 0).length); // 4
console.log(monthGrid(2026, 7, 1).length); // 6

February 2026 with Sunday first starts on a Sunday and has exactly 28 days, so it fits in four rows. August 2026 starts on a Saturday, so with Monday first it needs six. A calendar that always shows five rows would cut off 30 and 31 August. Always use weeks.length.

The full solution

The panel has monthGrid. It prints January 2026 as a grid of numbers and says where the 15th sits. The checks cover the row count, seven cells per row, both week starts, every day appearing once and February's six leading blanks. Press Run to see them.

The answer

const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();

function monthGrid(year, month, firstDayOfWeek) {
  const firstWeekday = new Date(year, month, 1).getDay();
  const lead = (firstWeekday - firstDayOfWeek + 7) % 7;      // blanks before the 1st

  const cells = [];
  for (let i = 0; i < lead; i++) cells.push(null);
  for (let day = 1; day <= daysInMonth(year, month); day++) cells.push(day);
  while (cells.length % 7 !== 0) cells.push(null);           // blanks after the last

  const weeks = [];
  for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
  return weeks;
}

const january = monthGrid(2026, 0, 1);        // Monday-first
const januarySunday = monthGrid(2026, 0, 0);  // Sunday-first

const row = january.findIndex((week) => week.includes(15));
const column = january[row].indexOf(15);

console.log('January 2026, Monday first:');
for (const week of january) {
  console.log(week.map((d) => (d === null ? '  ' : String(d).padStart(2))).join(' '));
}
console.log('the 15th sits at row', row, 'column', column);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('January 2026 needs five rows', january.length, 5);
test('every row has seven cells', january.every((week) => week.length === 7), true);
test('Monday-first, the month starts with three blanks', january[0], [null, null, null, 1, 2, 3, 4]);
test('and the last row trails off after the 31st', january[4], [26, 27, 28, 29, 30, 31, null]);
test('Sunday-first shifts everything on by one', januarySunday[0], [null, null, null, null, 1, 2, 3]);
test('and then needs no trailing blank at all', januarySunday[4], [25, 26, 27, 28, 29, 30, 31]);
test('the 15th is in the third row, on the Thursday', [row, column], [2, 3]);
test('every day of the month appears exactly once', january.flat().filter((d) => d !== null), Array.from({ length: 31 }, (unused, i) => i + 1));
test('February 2026 starts on a Sunday, so Monday-first needs six blanks', monthGrid(2026, 1, 1)[0], [null, null, null, null, null, null, 1]);

This is the shape a calendar component wants: a rectangular grid, so the markup is a plain nested loop with no arithmetic in the template, and null for the cells that are not part of the month. Everything else in this section shows up here — the zero-based month, the modular weekday gap from exercise 34, and day 0 of the next month for the length.

Note that the row count is not fixed. Most months need five rows, February in a common year starting on the first day of the week needs four, and a 31-day month starting late in the week needs six. Hard-coding five is a layout bug that appears a few times a year, which is long enough for nobody to remember what changed.

If you would rather show the neighbouring month's days in the blanks, as most calendars do, replace the nulls with dates from addDays around the ends and keep a flag saying which month each cell belongs to. The grid structure does not change.

Common mistakes

  • Forgetting the + 7 in the blank count. When the 1st's weekday number is smaller than the week's first day, you get a negative number and no blanks.
  • Hard-coding five rows. Some months need four and some need six.
  • Mixing up getDay() and getDate(). You need the weekday of the 1st, which is getDay().

Try it yourself

  1. Print the grid for August 2026 with day-name headings, like the January example above.
  2. Fill the blanks with the days from the previous and next month instead of null, and mark which month each belongs to.
  3. Write findCell(weeks, day) that returns the row and column of a day.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.