About this article
This article was created using an automated generation workflow leveraging generative AI. We reviewed MDN's documentation on array slice and tested pagination in Node.js using mock data.Verification status: Sample executed on Node.js v22.16.0 with 12 tests passed (browsers and live services not verified).
When you have 5 search results or product lists and want to display them 2 at a time, you calculate which slice of the array to extract based on the page number. Using JavaScript's slice allows you to extract the required range without destroying the original list. The key point is that while screen page numbers start at 1, array indices start at 0.
- First, extracting 5 items 2 at a time
- Why the start position is calculated by subtracting 1 from the page number
- Modifying a single location to understand the mechanism
- Encapsulating into functions to handle safe boundary conditions
- Original data is preserved, but pay attention to the contents of objects
- Actual test results and troubleshooting checks
- For professional use: The order of filtering, sorting, and pagination
- GitHub Sample
- Summary
- Official and Primary Sources
First, extracting 5 items 2 at a time
Prepare Node.js version 22. No additional libraries or network connection are required for execution. Save the following example to a file named page-example.mjs, and run node page-example.mjs in that folder. The strings A through E represent mock data for search results.
const items = ["A", "B", "C", "D", "E"]; const page = 2; const size = 2; // 人が使うページ番号から、配列の開始位置に変換する const start = (page - 1) * size; console.log(items.slice(start, start + size));
The expected result is that C and D are displayed on the screen. By changing the page number to 1, 3, and 4 and running the script, you can observe the following mappings. We actually verified these four conditions using the same 5 items in the full version of the training materials.
| Page | Start position | End position (exclusive) | Result |
|---|---|---|---|
| 1 | 0 | 2 | A, B |
| 2 | 2 | 4 | C, D |
| 3 | 4 | 6 | E |
| 4 | 6 | 8 | Empty array |
It is not abnormal for the last page to contain a single item. Since the array length is 5, attempting to retrieve up to index 6 does not forcefully pad non-existent positions. The fourth page returns an empty array because all items have already been retrieved. It is important not to confuse "no matches" on the UI with a program input error.
Why the start position is calculated by subtracting 1 from the page number
The first element A of the array is located at index 0. When a user selects page 1, 0 items are skipped; when page 2 is selected, the 2 items already displayed are skipped. For page 3, it is 4 items. Generalizing this, the number of items to skip is "(page number minus 1) × items per page".
The first argument of slice is the start index, and the second argument is the end boundary. Since the end boundary itself is not retrieved, a range from 0 to 2 yields 2 items at indices 0 and 1, which does not conflict with the start index 2 of the next page. If you mistake the second argument for the item count and always specify 2, the end position will be less than or equal to the start position for page 2 and beyond, resulting in an empty array.
Taking 5 items as an example, there is a boundary immediately after A and B, and another immediately after C and D. E spans from the final boundary to the end of the array. Comparing the start and end positions in the table reveals why adjacent pages share boundaries without sharing elements. For details, refer toMDN documentation on slice.
Modifying a single location to understand the mechanism
Change the items per page from 2 to 3, and increment the page number sequentially. Page 1 displays A, B, and C; page 2 displays D and E; page 3 is empty. Even with the same amount of data, the final page changes depending on the items per page. Math.ceil is used to calculate the final page. Rounding up 5 divided by 2 (2.5) yields 3, while rounding up 5 divided by 3 (approximately 1.67) yields 2. Even if there is only a fractional 1 item, that page is required.
In production list screens, when changing the items per page, either reset the page number to 1 or adjust the current page number to be within the new final page limit. For example, if you change a 3-item display to page 3 while viewing 2 items per page, there is no data on the modified page 3. Do not assume a search failure based solely on an empty array; verify the page numbers and total count before and after changing the item count.
Encapsulating into functions to handle safe boundary conditions
Writing the calculation formula in various places on the screen each time leads to bugs where page numbers are handled inconsistently in some parts. In the complete version, this is consolidated into a function named pageOf, separating the input and extraction processes. While regular page slicing involves short code, it is important not to use values received from outside directly in calculations.
Page number 0 is treated as an input error rather than "before the first page." Since the slice method interprets negative start positions as offsets from the end, calculating with page 0 as-is can unintentionally specify a range near the end of the array. Decimals, negative numbers, non-numeric strings, and Infinity are also rejected. The check using Number.isSafeInteger verifies not only the integer format but also whether the value falls within the range accurately handled by JavaScript's Number type.
The complete version throws a TypeError if the input is not an array, and a RangeError if the page number or item count is invalid. Even with a valid integer, an empty array is returned if it exceeds the final page. Because the final page is determined first, multiplying excessively large page numbers is avoided. Distinguishing these three cases allows the UI to appropriately guide the user regarding input errors, data format errors, or empty search results.
Original data is preserved, but pay attention to the contents of objects
The slice method returns a new array containing the extracted elements and does not modify the original array itself. For example, even if an item is added to the extracted array using push, it is not added to the original 5-element array. Because display data can be recreated from the same original array every time the search conditions change, this design is well-suited for separating display-only processing from data updates.
However, generating a new array is different from performing a deep copy of each element. When elements contain objects, it is a shallow copy that shares references to the same objects. Modifying the properties of an element in the display array will also affect the original data. When changing product names or statuses for display purposes, clarify the responsibility for modifications, such as creating separate objects exclusively for display. The course tests also include an item to verify this reference sharing.
Actual test results and troubleshooting checks
The complete version was syntax-checked and the demo was executed in Node.js v22.16.0. The display results for pages 1 through 4 matched the table above. Using the built-in Node.js testing features, all 12 test cases passed: first, middle, fractional, and out-of-range pages, empty arrays, item count changes, invalid pages and counts, non-array inputs, original array retention, shallow copying, and extremely large page numbers.
| Symptom | Things to check |
|---|---|
| The first element of every page is different | Are you subtracting 1 from the page number? |
| Nothing is displayed starting from the second page | Are you setting the end position to the start position plus the item count, rather than just the item count? |
| The result becomes empty after changing the item count | Did you compare the new final page with the current page? |
| A RangeError is thrown | Are you passing a positive safe integer? |
| node command is not found | Verify Node.js installation and check node –version |
Simply copying and running the code does not guarantee button operations in a browser or behavior in a live service. In this tutorial, we executed array processing within Node.js. We have not verified CodeQL, browsers, or live data connections.
For professional use: The order of filtering, sorting, and pagination
For example, on a screen filtering a hypothetical product list for "In Stock," items matching the condition are extracted first, then sorted in a specific order, and finally split into pages. If you paginate first and then apply the stock condition, you may end up with empty pages despite available display slots, or target products on other pages may become hidden. The search result count and total page count must also be calculated based on the filtered array.
If data is added midway through the list, the displayed contents may shift even on the same page number. Fixing the sorting criteria and determining the order of items with identical values using identifiers makes it easier to explain discrepancies upon redisplay. However, if the list itself continues to be updated, this alone cannot completely prevent duplication or omissions across pages. Server-side search result consistency and cursor-based pagination are separate design challenges.
Furthermore, slice is an operation that extracts a portion of an array already retrieved by JavaScript. Transferring tens of thousands of search results to the browser all at once and then displaying them 10 items at a time does not reduce the initial network transfer volume. Client-side pagination is straightforward for small amounts of static data, but for large datasets or scenarios requiring permission-based filtering, consider an approach where the server retrieves only the targeted subset. Input validation and access control are also required on the server side. Simply hiding a page does not restrict access to the underlying information.
GitHub Sample
Summary
By converting 1-based page numbers from the UI into 0-based array positions and leveraging the property that slice excludes its end index, fractional pages can be retrieved using the same formula. Distinguishing between input errors and valid empty arrays, as well as between array cloning and reference sharing, makes it easier to make decisions when designing list displays in practice.
