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)