Code Explainers

Javascript code explainers

javascript
const STORAGE_KEY = "theme-preference";
 
function getSystemTheme() {
  return window.matchMedia("(prefers-color-scheme: dark)").matches

Building a dark-mode toggle that respects the OS

dark-mode localstorage matchmedia
Intermediate 8 steps
javascript
'use client';
 
import { useRouter } from 'next/navigation';
import Link from 'next/link';

Archiving with router.refresh in Next.js

client-component data-mutation transitions
Intermediate 7 steps
javascript
import { useState, useRef, useCallback } from "react";
 
export function MultiSelect({ options, value, onChange, placeholder = "Select…" }) {
  const [open, setOpen] = useState(false);

Building a keyboard-accessible MultiSelect in React

controlled-component accessibility keyboard-navigation
Intermediate 10 steps
javascript
async function uploadInBatches(records, uploadFn, { batchSize = 100, concurrency = 3 } = {}) {
  const batches = [];
  for (let i = 0; i < records.length; i += batchSize) {
    batches.push(records.slice(i, i + batchSize));

Uploading records with bounded concurrency

concurrency worker-pool async-await
Advanced 8 steps
javascript
function formatPhoneNumber(value) {
  const digits = value.replace(/\D/g, '').slice(0, 10);
  const parts = [];
 

Building a live phone number input mask

input-masking regex dom-events
Intermediate 7 steps
javascript
import { NextResponse } from 'next/server';
 
const locales = ['en', 'fr', 'de', 'es'];
const defaultLocale = 'en';

Locale routing with Next.js middleware

middleware i18n content-negotiation
Intermediate 10 steps
javascript
const express = require('express');
const cookieParser = require('cookie-parser');
 
const router = express.Router();

Remember-me login with signed cookies in Express

authentication signed-cookies sessions
Intermediate 9 steps
javascript
const TOKEN_SPECS = [
  ["comment", /^\/\/[^\n]*|^\/\*[\s\S]*?\*\//],
  ["string", /^"(?:\\.|[^"\\])*"|^'(?:\\.|[^'\\])*'|^`(?:\\.|[^`\\])*`/],
  ["number", /^0[xX][\da-fA-F]+|^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/],

Building a syntax highlighter tokenizer

tokenizer regular-expressions lexing
Intermediate 8 steps
javascript
export async function compressImage(file, { maxWidth = 1600, maxHeight = 1600, quality = 0.8, mimeType = 'image/jpeg' } = {}) {
  const bitmap = await createImageBitmap(file);
 
  let { width, height } = bitmap;

Compressing images in the browser with canvas

canvas image-processing promises
Intermediate 7 steps
javascript
const express = require('express');
const multer = require('multer');
const path = require('path');
const crypto = require('crypto');

Safe image uploads with Multer in Express

file-upload multer validation
Intermediate 7 steps
javascript
const express = require('express');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
 

Refresh token rotation in Express

jwt token-rotation authentication
Advanced 9 steps
javascript
class StarRating {
  constructor(container, { max = 5, value = 0, onChange } = {}) {
    this.container = container;
    this.max = max;

Building an accessible star-rating widget

dom event-handling accessibility
Intermediate 7 steps
javascript
const form = document.querySelector('#signup-form');
const password = form.querySelector('#password');
const confirm = form.querySelector('#confirm-password');
const submit = form.querySelector('button[type="submit"]');

Live password-match validation in the DOM

form-validation dom-events accessibility
Intermediate 6 steps
javascript
const express = require('express');
const EventEmitter = require('events');
 
const router = express.Router();

Server-Sent Events with Express

server-sent-events streaming event-emitter
Advanced 8 steps
javascript
import { useState, useEffect, useCallback } from 'react';
 
export function useCountdown(initialSeconds) {
  const [secondsLeft, setSecondsLeft] = useState(initialSeconds);

Building a useCountdown hook in React

custom-hooks state-management side-effects
Intermediate 8 steps
javascript
import { useState, useRef } from "react";
 
export function TagInput({ initialTags = [], onChange }) {
  const [tags, setTags] = useState(initialTags);

Building a tag input in React

controlled-inputs state-management keyboard-handling
Intermediate 8 steps
javascript
import { NavLink, useLocation } from 'react-router-dom';
 
const NAV_ITEMS = [
  { to: '/', label: 'Dashboard', end: true },

Building an accessible Sidebar in React

routing accessibility declarative-ui
Intermediate 6 steps
javascript
function escapeHtml(str) {
  return str.replace(/[&<>"']/g, (ch) => ({
    '&': '&amp;',
    '<': '&lt;',

Safely highlighting search matches in text

html-escaping regex search-highlighting
Intermediate 7 steps