javascript
71 lines · 9 steps
A closure-based pagination helper in JS
A factory function keeps the current page private and exposes a small read/navigate API that the DOM renders against.
Explained by
highlit
1function usePagination(items, pageSize = 10) {
2 let currentPage = 1;
3 const totalPages = Math.max(1, Math.ceil(items.length / pageSize));
4
5 function clamp(page) {
6 return Math.min(Math.max(page, 1), totalPages);
7 }
8
9 function slice() {
10 const start = (currentPage - 1) * pageSize;
11 return items.slice(start, start + pageSize);
12 }
13
14 return {
15 get page() {
16 return currentPage;
17 },
18 get totalPages() {
19 return totalPages;
20 },
21 get hasPrevious() {
22 return currentPage > 1;
23 },
24 get hasNext() {
25 return currentPage < totalPages;
26 },
27 get items() {
28 return slice();
29 },
30 goTo(page) {
31 currentPage = clamp(page);
32 return slice();
33 },
34 next() {
35 return this.goTo(currentPage + 1);
36 },
37 previous() {
38 return this.goTo(currentPage - 1);
39 },
40 };
41}
42
43function renderControls(pager, container) {
44 container.innerHTML = `
45 <button data-action="prev" ${pager.hasPrevious ? "" : "disabled"}>Previous</button>
46 <span>Page ${pager.page} of ${pager.totalPages}</span>
47 <button data-action="next" ${pager.hasNext ? "" : "disabled"}>Next</button>
48 `;
49
50 container.querySelector('[data-action="prev"]').onclick = () => {
51 pager.previous();
52 renderList(pager);
53 renderControls(pager, container);
54 };
55 container.querySelector('[data-action="next"]').onclick = () => {
56 pager.next();
57 renderList(pager);
58 renderControls(pager, container);
59 };
60}
61
62function renderList(pager) {
63 const list = document.getElementById("list");
64 list.replaceChildren(
65 ...pager.items.map((item) => {
66 const li = document.createElement("li");
67 li.textContent = item.title;
68 return li;
69 })
70 );
71}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A factory function plus closure hides mutable state behind a controlled, read-only surface.
- 2Getters let callers observe derived state like hasNext without exposing the underlying variable.
- 3Keeping navigation and rendering separate means the UI just reacts to whatever the pager reports.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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/a-closure-based-pagination-helper-in-js-explained-javascript-fbe6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.