Calculate pagination (pages and offsets) in JavaScript
Advanced · 4 min read
When a list is too long for one screen, you split it into pages. Search results, online shops, admin tables and support inboxes all do this. Under the buttons that say "Previous", "Next" and "1 2 3 4 5" sits a small piece of arithmetic called pagination.
In this tutorial you will write paginate, a function that works out everything a page needs: how many pages there are, which items to show, whether Previous and Next should be active, and which page numbers to display. Our example is 97 support tickets, 10 to a page. You need to know functions, objects and Math.min and Math.max. The rest is explained here.
The words we'll use
- Total: how many items there are (97).
- Per page: how many fit on one page (10).
- Page: the page being viewed, counting from 1, the way people count.
- Offset (or start): the position in the array where that page begins. Arrays count from 0.
Page 1 starts at offset 0, page 2 at offset 10, page 3 at offset 20. So the start is (page - 1) * perPage.
Rounding up with Math.ceil
97 tickets at 10 a page fills 9 pages and leaves 7 over. Those 7 still need a page, so we always round up. Math.ceil does that:
console.log(97 / 10); // 9.7
console.log(Math.round(97 / 10)); // 10, but only by luck
console.log(Math.round(94 / 10)); // 9: the last 4 items vanish
console.log(Math.ceil(94 / 10)); // 10
Math.round and integer division sometimes give one page too few, and the items on the missing page simply disappear.
Here is the exercise. Try it on your own first if you like, or read on and we will build it in steps.
124 A paginator that survives the last page
hard97 tickets, 10 to a page. Work out the number of pages, the slice indices for the page being viewed, whether previous and next exist, and a window of at most five page numbers that stays five wide at both ends. Clamp a page number that is out of range.
Stuck? Three hints, smallest first
- 1. The page count is
Math.ceil, and zero items should still be one page. - 2. The slice is
(page - 1) * perPagetostart + perPage, capped at the total. - 3. Compute the window end first, then pull the start back from it, so the window cannot shrink at the far edge.
Step 1: count the pages and clamp the current one
function paginate(total, perPage, page) {
const pages = Math.max(1, Math.ceil(total / perPage));
const current = Math.min(Math.max(1, page), pages);
return { pages, current };
}
console.log(paginate(97, 10, 1)); // { pages: 10, current: 1 }
console.log(paginate(97, 10, 99)); // { pages: 10, current: 10 }
console.log(paginate(97, 10, 0)); // { pages: 10, current: 1 }
console.log(paginate(0, 10, 1)); // { pages: 1, current: 1 }
Math.max(1, ...) makes zero items still count as one page, so the screen can say "no tickets" instead of breaking.
The page number usually comes from the address bar, like ?page=99, and anyone can type anything there. Clamping means forcing a value into a range: Math.max(1, page) lifts it to at least 1, and Math.min(..., pages) caps it at the last page.
Step 2: work out the slice
function paginate(total, perPage, page) {
const pages = Math.max(1, Math.ceil(total / perPage));
const current = Math.min(Math.max(1, page), pages);
const start = (current - 1) * perPage;
const end = Math.min(start + perPage, total);
return { pages, current, start, end, hasPrev: current > 1, hasNext: current < pages };
}
const items = Array.from({ length: 97 }, (_, i) => 'ticket ' + (i + 1));
const last = paginate(97, 10, 10);
console.log(last.start, last.end); // 90 97
console.log(items.slice(last.start, last.end).length); // 7
console.log(items.slice(last.start, last.end)[0]); // ticket 91
console.log(last.hasPrev, last.hasNext); // true false
end is capped at the total, so the last page reports 97, not 100. slice would cope with 100 anyway, but these numbers are also shown to people, as in "showing 91 to 97 of 97".
hasPrev and hasNext tell the buttons whether to be active.
Step 3: a window of page numbers, first attempt
We want at most five page numbers, with the current page in the middle where possible. Math.floor(5 / 2) is 2, so start two pages before the current one:
function windowOf(current, pages, size = 5) {
const half = Math.floor(size / 2);
const from = Math.max(1, current - half);
const to = Math.min(pages, from + size - 1);
const numbers = [];
for (let p = from; p <= to; p++) numbers.push(p);
return numbers;
}
console.log(windowOf(1, 10)); // [ 1, 2, 3, 4, 5 ]
console.log(windowOf(6, 10)); // [ 4, 5, 6, 7, 8 ]
console.log(windowOf(10, 10)); // [ 8, 9, 10 ]
The start and the middle look right. On the last page, though, the window shrinks to three numbers, so the row of buttons changes width and the layout jumps as you get near the end.
Step 4: pull the start back
The fix: after finding to, move from back so the window is full width again, as long as there are enough pages.
function windowOf(current, pages, size = 5) {
const half = Math.floor(size / 2);
let from = Math.max(1, current - half);
const to = Math.min(pages, from + size - 1);
from = Math.max(1, to - size + 1); // pull back, so the width holds at the end
const numbers = [];
for (let p = from; p <= to; p++) numbers.push(p);
return numbers;
}
console.log(windowOf(10, 10)); // [ 6, 7, 8, 9, 10 ]
console.log(windowOf(9, 10)); // [ 6, 7, 8, 9, 10 ]
console.log(windowOf(1, 2)); // [ 1, 2 ]
Now the window stays five wide at both ends. When there are only two pages, Math.max(1, ...) stops from going below 1, and you get just the pages that exist.
The full solution
The answer panel puts all of this into one paginate(total, perPage, page, window = 5) function. It returns the page count, the clamped page, the slice, the page numbers and the two button flags, then prints page 1 and page 10 of the 97 tickets. Press Run to see the output.
function paginate(total, perPage, page, window = 5) {
const pages = Math.max(1, Math.ceil(total / perPage));
const current = Math.min(Math.max(1, page), pages);
const start = (current - 1) * perPage;
const end = Math.min(start + perPage, total);
const half = Math.floor(window / 2);
let from = Math.max(1, current - half);
const to = Math.min(pages, from + window - 1);
from = Math.max(1, to - window + 1); // pull back, so the width holds at the end
const numbers = [];
for (let p = from; p <= to; p++) numbers.push(p);
return { pages, current, start, end, numbers, hasPrev: current > 1, hasNext: current < pages };
}
const items = Array.from({ length: 97 }, (_, i) => 'ticket ' + (i + 1));
const p1 = paginate(97, 10, 1);
const p10 = paginate(97, 10, 10);
const zero = paginate(0, 10, 1);
console.log('page 1 of', p1.pages, p1.numbers, 'page 10', p10.numbers);
console.log('last page holds', items.slice(p10.start, p10.end).length, 'tickets');
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.
test('97 tickets at 10 a page is 10 pages', p1.pages, 10);
test('the first page slices from the start and has nothing before it', [p1.start, p1.end, p1.hasPrev], [0, 10, false]);
test('the last page is the short one, and its first ticket is 91', [p10.start, p10.end, items.slice(p10.start, p10.end).length, items.slice(p10.start, p10.end)[0]], [90, 97, 7, 'ticket 91']);
test('the window starts at one and there is no page before it', [p1.numbers, p1.hasNext], [[1, 2, 3, 4, 5], true]);
test('at the far end it is still five wide, not one', [p10.numbers, p10.hasNext], [[6, 7, 8, 9, 10], false]);
test('in the middle it centres on the current page', paginate(97, 10, 6).numbers, [4, 5, 6, 7, 8]);
test('a page number out of range is clamped at both ends', [paginate(97, 10, 99).current, paginate(97, 10, 0).current], [10, 1]);
test('no items is still one page, with an empty slice', [zero.pages, zero.start, zero.end, zero.numbers], [1, 0, 0, [1]]);
test('fewer pages than the window gives only the pages there are', paginate(20, 10, 1).numbers, [1, 2]);
Two lines carry the weight. Math.ceil for the page count, because 97 items at 10 a page is 10 pages and Math.round or integer division gives 9 and hides the last seven tickets — a data-loss bug that only appears when the total is not a multiple of the page size. And Math.min(start + perPage, total) for the end, so the final page reports 7 rather than 10; slice would have clamped it anyway, but the number is also shown to the user as "91 to 100 of 97".
The window is the part worth studying. Centring naively — current - 2 to current + 2 — gives three numbers on page 9 and two on page 10, so the control changes width as you approach the end and the layout jumps. Computing to first, then pulling from back to to - window + 1, keeps the width constant until there genuinely are not that many pages, which the last assertion checks. Clamping current matters because the page number arrives from a URL a user can edit: unclamped, ?page=99 gives a negative-free but empty slice and a paginator with no way back.
Common mistakes
- Using
Math.roundorMath.floorfor the page count. Whenever the total isn't a multiple of the page size, you can lose the last page. - Trusting the page number from the URL. Clamp it, or
?page=99shows an empty page with no way back. - Centering the window without pulling it back. It shrinks near the last page and the buttons jump around.
Try it yourself
- Add a
labelto the result, like'Showing 91 to 97 of 97'. Make it say'No tickets'when the total is 0. - Change the window size to 7 and check pages 1, 4 and 10.
- Write
pageOf(index, perPage)that tells you which page a given item lands on. Item 0 is on page 1 and item 90 on page 10.