javascript
37 lines · 9 steps
Building a text calendar in JavaScript
Turn a year and month into a grid of weeks, then render it as an aligned ASCII calendar.
Explained by
highlit
1function generateCalendarGrid(year, month) {
2 const firstDay = new Date(year, month, 1);
3 const lastDay = new Date(year, month + 1, 0);
4 const daysInMonth = lastDay.getDate();
5 const startWeekday = firstDay.getDay();
6
7 const weeks = [];
8 let week = new Array(7).fill(null);
9
10 for (let day = 1; day <= daysInMonth; day++) {
11 const weekday = (startWeekday + day - 1) % 7;
12 week[weekday] = day;
13 if (weekday === 6 || day === daysInMonth) {
14 weeks.push(week);
15 week = new Array(7).fill(null);
16 }
17 }
18
19 return weeks;
20}
21
22function renderCalendar(year, month) {
23 const monthName = new Date(year, month).toLocaleString('default', { month: 'long' });
24 const headers = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
25 const weeks = generateCalendarGrid(year, month);
26
27 const cell = (v) => (v === null ? ' ' : String(v).padStart(2, ' '));
28 const lines = [];
29
30 lines.push(`${monthName} ${year}`.padStart(11 + Math.floor((monthName.length + 5) / 2)));
31 lines.push(headers.join(' '));
32 for (const week of weeks) {
33 lines.push(week.map(cell).join(' '));
34 }
35
36 return lines.join('\n');
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Passing day 0 of the next month is a clean trick to get the last day of the current one.
- 2Modular arithmetic maps a running day count onto fixed weekday columns without branching.
- 3Separating grid generation from rendering keeps the date logic reusable and the output swappable.
Related explainers
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
Intermediate
7 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-text-calendar-in-javascript-explained-javascript-e098/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.