Code Explainers

Javascript code explainers

javascript
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
 
export function formatBytes(bytes, { decimals = 1, binary = false } = {}) {
  if (!Number.isFinite(bytes)) {

Formatting byte counts into human units

logarithms formatting default-parameters
Intermediate 8 steps
javascript
'use client';
 
import { useState, useTransition, useRef, useEffect, useCallback } from 'react';
import { loadMorePosts } from '@/app/actions/posts';

Infinite scroll with Server Actions in Next.js

infinite-scroll intersection-observer server-actions
Intermediate 8 steps
javascript
import { createContext, useContext, useEffect, useState, useCallback } from 'react';
 
const ThemeContext = createContext(null);
 

Building a theme provider with React Context

context hooks dark-mode
Intermediate 9 steps
javascript
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);

Building a curry function in JavaScript

currying closures higher-order-functions
Intermediate 7 steps
javascript
import { useState } from 'react';
 
const steps = ['account', 'profile', 'review'];
 

Building a multi-step form wizard hook in React

custom-hooks form-validation state-management
Intermediate 9 steps
javascript
function splitFullName(fullName) {
  const cleaned = (fullName || '').trim().replace(/\s+/g, ' ');
 
  if (!cleaned) {

Parsing full names into first and last

string-parsing regex edge-cases
Intermediate 8 steps
javascript
import { db } from '@/lib/db'
 
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://example.com'
 

Generating a dynamic sitemap in Next.js

sitemap seo database-query
Intermediate 5 steps
javascript
class TokenBucket {
  constructor({ capacity, refillPerSecond }) {
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;

How token-bucket rate limiting works in Express

rate-limiting token-bucket middleware
Intermediate 7 steps
javascript
import { useState, useRef, useCallback, useLayoutEffect } from "react";
 
export function useResizeObserver({ debounce = 0 } = {}) {
  const [size, setSize] = useState({ width: 0, height: 0 });

A resize-observing hook in React

custom-hook resizeobserver callback-ref
Advanced 8 steps
javascript
import { useState } from "react";
 
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
 

Building a validated signup form in React

form-validation controlled-components state-management
Intermediate 10 steps
javascript
import { useRef, useState, useCallback, useMemo } from 'react';
 
export function VirtualList({ items, rowHeight = 40, height = 600, overscan = 5, renderRow }) {
  const [scrollTop, setScrollTop] = useState(0);

How a virtualized list works in React

virtualization performance memoization
Intermediate 8 steps
javascript
const express = require('express');
const router = express.Router();
const db = require('../db');
 

Building a paginated articles endpoint in Express

pagination input-validation async-await
Intermediate 8 steps
javascript
import { useState, useCallback, memo } from 'react';
 
const TodoItem = memo(function TodoItem({ todo, onToggle, onRemove }) {
  return (

Preventing re-renders in a React todo list

memoization usecallback referential-stability
Intermediate 8 steps
javascript
import { useState, useEffect, useRef, useCallback } from "react";
 
function useDebouncedValue(value, delay) {
  const [debounced, setDebounced] = useState(value);

Debounced autosave in React

debouncing custom-hooks abort-controller
Intermediate 8 steps
javascript
import { lazy, Suspense } from "react";
import { Routes, Route, NavLink } from "react-router-dom";
import ErrorBoundary from "./components/ErrorBoundary";
import Spinner from "./components/Spinner";

Lazy-loaded routes in React

code-splitting lazy-loading routing
Intermediate 6 steps
javascript
import { NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
 
const PROTECTED_PREFIXES = ['/dashboard', '/settings', '/billing'];

Gating routes with Next.js middleware and JWTs

authentication middleware jwt
Intermediate 8 steps
javascript
const express = require('express');
const session = require('express-session');
const RedisStore = require('connect-redis').default;
const { createClient } = require('redis');

Redis-backed session auth in Express

sessions authentication redis
Intermediate 8 steps
javascript
function parseJwtPayload(token) {
  const parts = token.split('.');
  if (parts.length !== 3) {
    throw new Error('Invalid JWT: expected 3 segments');

Decoding a JWT payload in JavaScript

jwt base64url encoding
Intermediate 6 steps