DEV Community


Discussion on: How (and Why) To Implement a Stack in JavaScript

jorgecc profile image
Jorge Castro

C# has a Stack class defined in the framework and it has the functionality of peek. Why Peek? Sometimes we want to know what it's the "over-top" value (i.e. the last one) without removing it.

It's pretty easy to implement peek, it's exactly like pop but without pop.

this.peek= function() {
    if (this.size === 0) {
      console.log(`nothing here`);
    let lastKey = this.size - 1;
    let result =[lastKey];
    return result;

Why LIFO anyways?

Let's say you are running a company in Australia that sells toilet paper.

And it is your stock

let paper= new Stack(5);
paper.push(`Regular paper`);
paper.push(`Premium one`);
paper.push(`2ply paper`);

But then, suddenly Aussies got crazy purchasing toilet paper.


paper.pop(); // Stack underflow!

You don't want to runs out of stock, so you buy more paper but also you want to sell your recent paper because it's a cheap product that you could sell in quantities and the customers can't bargain because the hype to buy paper.

paper.push(`generic paper`);
mattpopovich profile image
Matt Popovich Author

Great points! :)

Forem Open with the Forem app