history.go() for Jumping Multiple Steps
What you'll learn: How to jump forward or backward through multiple history entries at once using history.go().
Beyond One Step at a Time
You've already learned history.back() and history.forward() to move one entry at a time through the browser's history stack. But what if you need to jump back three pages? Or skip forward two entries? That's where history.go() comes in.
How history.go() Works
The history.go() method accepts a single integer argument that tells the browser how many steps to move:
- Positive numbers move forward in history
- Negative numbers move backward in history
- Zero refreshes the current page
// Go back 2 pages in history
history.go(-2);
// Go forward 3 pages in history
history.go(3);
// Refresh the current page
history.go(0);
Think of it like an elevator: Instead of pressing the button multiple times to go up or down one floor at a time, you can directly select floor "-2" (two levels down) or "+3" (three levels up).
Practical Considerations
If you try to jump beyond the available history entries (for example, history.go(-10) when only 3 entries exist), the browser simply does nothing—no error is thrown.
// Jump to the very beginning of this session
// (if user visited 5 pages)
history.go(-4);
// Return to where you were
history.go(4);
This is particularly useful for "back to start" functionality or when implementing complex navigation patterns where you know exactly how many steps back you need to go.
Key Takeaway: Use history.go(n) to jump multiple history entries in a single call—negative values move backward, positive values move forward, and zero refreshes the page.