Stack (Implementation)
Explore the step-by-step implementation of a stack in JavaScript using arrays. Understand core stack operations such as push, pop, isEmpty, getTop, and size, along with their time complexities. This lesson helps you master stack functionality essential for coding interviews and practical programming.
Introduction
Most programming languages come with the Stack data structure built-in. However, we will be implementing a stack from scratch, which will allow you to truly master the ins-and-outs of the data structure.
Implementation
Stacks can be implemented using Arrays or Linked Lists. Each implementation has its own advantages and disadvantages. Here, however, we will show an implementation of stacks using arrays.
As mentioned in the previous lesson, a typical Stack must contain the following functions:
push(element)pop()isEmpty()getTop()size()
We will take a close look at these functions individually, but before we do, let’s construct a Stack class and create an object. This class will consist of the member functions given above and array that will hold all the elements of the stack. Additionally, we’ll also have a variable (this.top) to specify the top of the stack.
Implementing isEmpty(), getTop() and size()
Before adding the push(element) and pop() functions into this code, let’s implement the following functions:
isEmpty()getTop()size()
Examine the following code.
The isEmpty() function returns the boolean you get from comparing the length of the array to 0. If the length of the array is 0, then the function will return True. Otherwise, it will return False.
If the array is not empty, the getTop() function returns the last element in the array, which we are considering to be the top of the stack!
Note In the
getTop()method; we have added codeif (this.items.length == 0)(line 8 and 9) to return null for greater clarity, but this is optional as we have already set thethis.top = nullin the constructor if no elements are added, so thegetTop()method will return null if the length of the stack is zero, either way. Try it yourself by commenting lines 8 and 9. :)
Implementing push(element) and pop()
Now, study the implementation of the push(element) and pop() functions.
If you look at the output of the code, you can see that the elements popped out of the stack in the exact reverse order that they were pushed in. That means our Stack works perfectly. Congratulations, you have successfully implemented a Stack using a JavaScript array!
Complexities of Stack Operations
Let’s look at the time complexity of each stack operation.
| Operation | Time Complexity |
|---|---|
| isEmpty | O(1) |
| getTop | O(1) |
| size | O(1) |
| push | O(1) |
| pop | O(1) |