By Hemanta Sundaray on 2021-07-19
A stack is a vertical array with the following 3 constraints:
You can think of a stack as a stack of dishes, one on top of the other.
As you can see, the first item in the array becomes the bottom of the stack, while the last item becomes the stack’s top.
We will push a 1 onto the stack. Next, we will push a 10 and finally a 100.
As you can see, we always add data to the top (that is, the end) of the stack.
Now, let’s pop some items. Because of a stack’s restrictions, we can only pop data from the top. First we pop the 100, next we pop the 10 and our stack contains only the number 1.
A term that is used to describe the operations we can perform on a stack is LIFO (Last In First Out). All this means is that the last item pushed onto a stack is always the first item popped from it.
A stack is an abstract data type - it is built on top of other built-in data structures. In our case, we will use arrays, which are built-in data structures in JavaScript.
We will implement a stack data structure using JavaScript classes.
class Stack {
constructor() {
this.data = []
}
add(element) {
return this.data.push(element)
}
remove() {
return this.data.pop()
}
peek() {
return this.data[this.data.length - 1]
}
}
const stackOne = new Stack()
stackOne.add(1)
stackOne.add(10)
stackOne.add(100)
console.log(stackOne)
// Stack { data: [ 1, 10, 100 ] }
stackOne.remove()
console.log(stackOne)
// Stack { data: [ 1, 10 ] }
console.log(stackOne.peek())
// 10
Whenever we create a new instance of the Stack class, JavaScript will invoke the constructor method to build an empty array, where we store our data.
The Stack class contains 3 methods that push new elements to the data array, pop elements from the data array and read elements from the data array.