Bird
Raised Fist0
Node.jsframework~20 mins

Pagination patterns in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pagination Pro
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this cursor-based pagination snippet?

Consider this Node.js function that fetches items using cursor-based pagination. What will be the value of nextCursor after fetching the first page?

Node.js
async function fetchPage(cursor = null) {
  const pageSize = 3;
  const allItems = ['a', 'b', 'c', 'd', 'e', 'f'];
  let startIndex = 0;
  if (cursor) {
    startIndex = allItems.indexOf(cursor) + 1;
  }
  const pageItems = allItems.slice(startIndex, startIndex + pageSize);
  const nextCursor = pageItems.length === pageSize ? pageItems[pageItems.length - 1] : null;
  return { pageItems, nextCursor };
}

(async () => {
  const result = await fetchPage();
  console.log(result.nextCursor);
})();
A"c"
B"d"
Cnull
D"f"
Attempts:
2 left
💡 Hint

Look at how nextCursor is assigned based on the length of pageItems.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements offset-based pagination in Node.js?

Given a list of items, which code snippet correctly returns a page of items using offset and limit?

Node.js
const items = ['x', 'y', 'z', 'w', 'v'];
function getPage(offset, limit) {
  // return a slice of items
}
Areturn items.slice(limit, offset + limit);
Breturn items.slice(offset, limit);
Creturn items.slice(offset + limit);
Dreturn items.slice(offset, offset + limit);
Attempts:
2 left
💡 Hint

Remember that slice(start, end) uses start inclusive and end exclusive.

🔧 Debug
advanced
2:00remaining
Why does this cursor pagination code cause an infinite loop?

Examine the following code snippet for cursor pagination. Why might it cause an infinite loop when fetching pages?

Node.js
async function fetchPages() {
  let cursor = null;
  while (true) {
    const { items, nextCursor } = await fetchPage(cursor);
    if (!nextCursor) break;
    cursor = cursor;
  }
}
AThe cursor is never updated, so the loop never ends.
BThe fetchPage function returns an empty array causing no break.
CThe break condition is incorrect; it should check items length.
DThe while loop syntax is invalid causing runtime error.
Attempts:
2 left
💡 Hint

Check how the cursor variable changes inside the loop.

🧠 Conceptual
advanced
2:00remaining
What is a key advantage of cursor-based pagination over offset-based pagination?

Choose the best explanation for why cursor-based pagination is often preferred for large datasets.

ACursor-based pagination requires no state to be stored between requests.
BCursor-based pagination avoids skipping or duplicating items when data changes during pagination.
COffset-based pagination uses less memory than cursor-based pagination.
DCursor-based pagination always loads all data at once, improving speed.
Attempts:
2 left
💡 Hint

Think about what happens if data is added or removed while paginating.

❓ state_output
expert
3:00remaining
What is the final value of page after this asynchronous offset pagination loop?

Given the following code, what will be the value of page after the loop finishes?

Node.js
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const pageSize = 2;
let offset = 0;
let page = [];

async function getPage(offset, limit) {
  return items.slice(offset, offset + limit);
}

(async () => {
  while (true) {
    page = await getPage(offset, pageSize);
    if (page.length === 0) break;
    offset += pageSize;
  }
  console.log(page);
})();
A["f", "g"]
B["g"]
C[]
D["e", "f"]
Attempts:
2 left
💡 Hint

Consider what happens when the last page is fetched and the loop breaks.

Practice

(1/5)
1.

What is the main purpose of pagination in a Node.js application?

easy
A. To combine all data into one large response
B. To split large data into smaller pages for faster loading and better user experience
C. To delete old data automatically
D. To encrypt data before sending it to the client

Solution

  1. Step 1: Understand pagination concept

    Pagination divides data into smaller chunks or pages to avoid loading everything at once.
  2. Step 2: Identify the benefit in Node.js apps

    This improves speed and usability by sending only a subset of data per request.
  3. Final Answer:

    To split large data into smaller pages for faster loading and better user experience -> Option B
  4. Quick Check:

    Pagination = split data for speed [OK]
Hint: Pagination means splitting data into pages for faster loading [OK]
Common Mistakes:
  • Thinking pagination deletes data
  • Confusing pagination with encryption
  • Assuming pagination combines all data
2.

Which of the following is the correct way to use limit and offset for pagination in a SQL query within Node.js?

SELECT * FROM users ORDER BY id ASC LIMIT ? OFFSET ?;
easy
A. limit = number of items per page, offset = (page number - 1) * number of items per page
B. limit = page number, offset = number of items per page
C. limit = total items, offset = 0
D. limit = number of items per page, offset = page number

Solution

  1. Step 1: Understand limit and offset roles

    Limit controls how many items to fetch; offset skips items before starting.
  2. Step 2: Calculate offset for pagination

    Offset should skip items from previous pages: (page number - 1) * items per page.
  3. Final Answer:

    limit = number of items per page, offset = (page number - 1) * number of items per page -> Option A
  4. Quick Check:

    Offset skips previous pages = (page-1)*limit [OK]
Hint: Offset skips previous pages: (page-1) times limit [OK]
Common Mistakes:
  • Using offset as page number directly
  • Swapping limit and offset values
  • Setting offset to page number without calculation
3.

Given this Node.js code snippet using a database query for pagination:

const page = 3;
const limit = 10;
const offset = (page - 1) * limit;
const results = await db.query('SELECT * FROM products ORDER BY id ASC LIMIT ? OFFSET ?', [limit, offset]);
console.log(results.length);

If the database has 25 products, what will results.length print?

medium
A. 25
B. 10
C. 15
D. 5

Solution

  1. Step 1: Calculate offset and limit values

    Page 3 means offset = (3-1)*10 = 20, limit = 10.
  2. Step 2: Determine how many products remain after offset

    There are 25 products total, offset 20 skips first 20, leaving 5 products.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Remaining items after offset = 5 [OK]
Hint: Last page may have fewer items than limit [OK]
Common Mistakes:
  • Assuming full limit items always returned
  • Calculating offset incorrectly
  • Ignoring total number of products
4.

Identify the error in this Node.js pagination code snippet:

const page = 0;
const limit = 10;
const offset = page * limit;
const results = await db.query('SELECT * FROM items LIMIT ? OFFSET ?', [limit, offset]);

What is the problem with this code?

medium
A. Offset should be negative for first page
B. Limit should be zero to fetch all items
C. Page number should start from 1, not 0, causing incorrect offset
D. Query syntax is invalid with placeholders

Solution

  1. Step 1: Check page number usage

    Page is set to 0, but pagination usually starts at 1.
  2. Step 2: Calculate offset impact

    Offset = 0 * 10 = 0, so it fetches first page, but page 0 is invalid logically.
  3. Final Answer:

    Page number should start from 1, not 0, causing incorrect offset -> Option C
  4. Quick Check:

    Page numbering starts at 1 [OK]
Hint: Page numbers start at 1, not 0 [OK]
Common Mistakes:
  • Using page 0 as valid page
  • Setting limit to zero incorrectly
  • Misunderstanding offset calculation
5.

You want to implement cursor-based pagination in Node.js for a real-time chat app. Which approach is best to fetch the next page of messages?

// Current last message ID is stored in lastMessageId
const query = 'SELECT * FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?';
const results = await db.query(query, [lastMessageId, limit]);

Why is this approach better than using offset?

hard
A. Cursor pagination avoids skipping items and handles new data better than offset
B. Offset pagination is faster for real-time data
C. Cursor pagination requires less code but is less reliable
D. Offset pagination works better with unordered data

Solution

  1. Step 1: Understand cursor pagination

    Cursor uses a unique ID to fetch next items after the last seen message.
  2. Step 2: Compare with offset pagination

    Offset can skip or repeat items if data changes during pagination; cursor avoids this.
  3. Final Answer:

    Cursor pagination avoids skipping items and handles new data better than offset -> Option A
  4. Quick Check:

    Cursor = stable pagination with changing data [OK]
Hint: Cursor uses last ID to avoid skipping new data [OK]
Common Mistakes:
  • Thinking offset is better for real-time data
  • Assuming cursor is less reliable
  • Confusing cursor with offset usage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard