Peeking the top of the stack and clearing it

In the last section, we learned that, in order to access the element that is stored at the top of the stack, it is necessary to decrement the count property by 1. So let's see the code for the peek method:

peek() {  if (this.isEmpty()) {    return undefined;  }  return this.items[this.count - 1];}

And to clear the stack, we can simply reset it to the same values we used in the constructor:

clear() {  this.items = {};  this.count = 0;}

We could also use the following logic to remove all elements from the stack, respecting the LIFO behavior:

while (!this.isEmpty()) {  this.pop();}

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.