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
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)