Implementing a Stack Data Structure with JavaScript
As part of our goal to publish an article about every data structure listed as must-have knowledge in Gayle’s Cracking the Coding Interview, this article will explore the stack data structure.
As a programmer, you will often encounter situations where you need to store and retrieve data in a specific way. There are many such ways to accomplish this task – one such way is by using a data structure called a stack. In this article, we will explore the concept of the stack data structure and implement one using JavaScript.
What is a stack?
A stack is a collection of elements that are organized in a specific way. It follows the Last In First Out (LIFO) principle, meaning that the last element that was added to the stack will be the first one to be removed. Think of it as a stack of plates in a buffet, where the last plate that was placed on top of the stack is the first one to be picked up.
Stacks are commonly used in programming for tasks such as handling function calls, keeping track of undo/redo operations (such as the forward and back tabs in your browser), and parsing expressions.
Implementing a stack
To implement a simple stack, we can use an array, making use of the push()
and pop()
methods to add and remove elements.
const stack = [];
// Add elements
stack.push(1);
stack.push(2);
stack.push(3);
// Remove the last element
stack.pop();
// Add another element
stack.push(4);
// Log the elements to console
console.log(stack); // Output: [ 1, 2, 4 ]
That’s it! A very simple implementation of a stack data structure using an array. Let’s go a step further and implement a stack using a class.
Creating a stack class
While using an array works fine for simple applications, we can use a class to implement a stack in a more organized and efficient way. Our Stack class should have push()
, pop()
, and peek()
methods. We should also include two additional methods, isEmpty()
, that returns true
if the stack is empty, and printStack()
, that returns a string representation of the stack. Let’s implement this!
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) {
return "Underflow";
}
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
printStack() {
let str = "";
for (let i = 0; i < this.items.length; i++) {
str += this.items[i] + " ";
}
return str;
}
}
There we have it, a class implementation of the stack data structure. Let’s take a look at how to use it.
Using the stack
We actually want to test our stack and get a better idea of how it works. Let’s use the stack class to perform some operations:
// Create a new stack
let stack = new Stack();
// Add elements to the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Print the current state of the stack
console.log(stack.printStack()); // 1 2 3
// Remove an element from the stack
stack.pop();
// Print the current state of the stack
console.log(stack.printStack()); // 1 2
// Get the top element of the stack
console.log(stack.peek()); // 2
// Check if the stack is empty
console.log(stack.isEmpty()); // false
In the code above, we create a new Stack object and add elements to it using the push()
method. We then print the current state of the stack using the printStack()
method, which returns a string representation of the stack. We remove an element from the stack using the pop()
method and print the current state of the stack again. We then use the peek()
method to get the top element of the stack, which is 2
. Finally, we use the isEmpty()
method to check if the stack is empty, which returns false
.
Conclusion
Stacks are a useful data structure for storing and retrieving elements in a specific order. They follow the Last In First Out (LIFO) principle and can be implemented using arrays or classes in JavaScript.
In this article, we learned how to implement a stack using both an array and a class. With this knowledge, you can start using stacks in your own projects to make your code more organized and efficient.
If you’d like to explore more data structures, follow the links:
Master the coding interview
If you want to explore data structures and algorithms via a video course, taught by an amazing instructor, Andrei Neagoi, Zero to Mastery has a great course for you: Master the Coding Interview: Data Structures + Algorithms.
In this course, you will:
- Ace coding interviews given by some of the top tech companies.
- Learn to implement and use different data structures.
- Learn the notorious Big-O notation.
- Become more confident and prepared for your next coding interview.
Get 10% off by using code FRIENDS10.
FAQ
Q: What is a stack data structure?
A: A stack is a linear data structure in which elements can be inserted and removed from only one end. It follows the Last-In-First-Out (LIFO) principle.
Q: What are the operations supported by a stack?
A: A stack supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Other operations may include peek, which returns the top element without removing it, and isEmpty, which checks if the stack is empty.
Q: What is the time complexity of push and pop operations in a stack?
A: The time complexity of push and pop operations in a stack is O(1) on average, which means it takes constant time to perform these operations regardless of the size of the stack.
Q: How is a stack different from a queue?
A: A stack follows the Last-In-First-Out (LIFO) principle, while a queue follows the First-In-First-Out (FIFO) principle. In a queue, elements are inserted at the rear and removed from the front, while in a stack, elements are inserted and removed from the top.
Q: What are some real-world examples of using a stack data structure?
A: Some examples of using a stack in real-world applications include the undo and redo functionality in text editors, the back and forward buttons in web browsers, and the call stack in programming languages.
Q: Can a stack be implemented using an array or a linked list?
A: Yes, a stack can be implemented using both arrays and linked lists. In an array-based implementation, elements are stored in a contiguous block of memory, while in a linked-list based implementation, elements are stored in nodes that are linked together.
Q: What is the maximum size of a stack?
A: The maximum size of a stack depends on the underlying implementation and the amount of available memory. In practice, the size of a stack is usually limited by the amount of available memory and the operating system’s stack size limit.
Q: What is a stack overflow error?
A: A stack overflow error occurs when the stack size exceeds its limit, usually due to an infinite or excessively deep recursion, or due to a large number of function calls without releasing the memory.
Disclosure: We are affiliated with ZTM (Zero to Mastery), so if you happen to be interested in the course above and purchase it through our link, we will recieve a small commission of the sale (at no extra cost to you). Please also note that we have browsed ZTM courses and have found them to be some of the best material on the web. We don’t recommend them solely for personal gain.
Thank you for the support!
Related Posts
The Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating a Real Time Chat Application with React, Node, and TailwindCSS
In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.
Read more