DEV Community

Gift Egbonyi
Gift Egbonyi

Posted on • Edited on

Understanding Stacks in JavaScript

Hey friends ๐Ÿ‘‹

Itโ€™s another Tutorial Wednesday, and today weโ€™re learning about one of the simplest data structures: Stacks.

Think of a stack like a pile of plates ๐Ÿฝ๏ธ:

  • You add a plate on top โ†’ push()
  • You remove the top plate โ†’ pop()
  • You just want to see the top plate โ†’ peek()

This system is called LIFO (Last In, First Out). The last item you put in is the first one to come out.


Implementing a Stack in JavaScript

class Stack {
  constructor() {
    this.items = [];
  }

  // Add item
  push(element) {
    this.items.push(element);
  }

  // Remove top item
  pop() {
    return this.items.pop();
  }

  // See top item
  peek() {
    return this.items[this.items.length - 1];
  }

  // Check if empty
  isEmpty() {
    return this.items.length === 0;
  }

  // Size of stack
  size() {
    return this.items.length;
  }
}

// Example usage
const stack = new Stack();
stack.push("Plate 1");
stack.push("Plate 2");
console.log(stack.peek()); // Plate 2
stack.pop();
console.log(stack.peek()); // Plate 1
Enter fullscreen mode Exit fullscreen mode

Try It Yourself

Hereโ€™s a live playground where you can push, pop and peek items in a stack:

๐Ÿ‘‰ Play with the Stack on CodePen


Real-World Uses of Stacks

  • Undo/Redo in text editors
  • Browser history (back/forward buttons)
  • Function call stack in JavaScript

๐Ÿ™‹๐Ÿฝโ€โ™€๏ธ Over to You!

Try expanding this stack:

  • Add a Clear Stack button
  • Show the entire stack visually as a vertical list
  • Limit stack size (like a plate rack with max capacity)

Next Wednesday, weโ€™ll explore Queues โ€” the opposite of stacks, FIFO (First In, First Out). Stay tuned!

Let me know if you do the challenge! I'd like to see yours! Connect with me on GitHub

Was this tutorial helpful? Got questions? Or any insight to help me write better tutorials? Let me know in the ๐Ÿ’ฌ!


Thatโ€™s it for todayโ€™s midweek mini tutorial!

Iโ€™m keeping things light, fun and useful; one small project at a time.

If you enjoyed this, leave a ๐Ÿ’ฌ or ๐Ÿงก to let me know.

And if youโ€™ve got an idea for something you'd like me to try out next Wednesday, drop it in the comments. ๐Ÿ‘‡

Follow me to see more straight-forward and short tutorials like this :)

If you are curious about what I do, check out my Portfolio

:-)

Web trails
You can also find me here on LinkedIn
or here X (Twitter)

โœ๐Ÿพ Iโ€™m documenting my learning loudly every Wednesday. Follow along if you're learning JavaScript too!
Letโ€™s keep learning together!

See you next Wednesday ๐Ÿš€

Top comments (0)