Navigating to a New Page
When you visit a new URL, what happens? The browser should add it to your history, right? Let's code that part:
JAVASCRIPT
1visit(url) {
2 this.history = this.history.slice(0, this.pointer + 1);
3 this.history.push(url);
4 this.pointer++;
5}What's happening here?
- We first trim the history array up to the current pointer. This is essential because if you navigate to a new URL from a past page, the future history should be erased.
- The new URL is pushed into the
historyarray. - The
pointeris incremented to point to the new current URL.
Moving Back and Forth in History
Now, let's implement the methods that allow us to go back and forth in our browser history:
JAVASCRIPT
1back() {
2 this.pointer = Math.max(0, --this.pointer);
3 return this.history[this.pointer];
4}
5
6forward() {
7 this.pointer = Math.min(this.history.length - 1, ++this.pointer);
8 return this.history[this.pointer];
9}What's happening here?
back(): Decreases thepointerbut ensures it doesn't go below 0 usingMath.max().forward(): Increases thepointerbut ensures it doesn't exceed the length of thehistoryarray usingMath.min().


