The if block checks whether the counter (which you'll remember, was counting the number of records we looped over) is less than the value in pageSize. If that's the case, then that means we didn't find enough records to finish even the current page, so it's a fair bet that there isn't a next page.

Now in 999 cases out of a thousand, if the counter is the same as the pageSize, we can assume that there are more records left after the end of this page. However, we can't be 100% certain unless we check... but, we don't want to impact performance.

The else block does this by setting a new window that will contain only one record (to minimize the size of the query).

In fact, it occurs to me that we could further reduce the performance hit by a tiny amount if we instead set the first window to one more than the pageSize limit, stopped iterating over the GlideRecord once the counter hit the same value as pageSize, and returned the value of gr.hasNext() at that point, but I've already written most of this article so I'm not going to go back and change it! I will however, include the improved-performance logic in the tool you can download from the link at the end of this article. 😉

So that's all there is for the core logic. Let's have a look at the whole thing, all put together!