JavaScript Data Structures: Stack (pt. 2)

Esther 승연 Kang
2 min readApr 11, 2021

Last week, I introduced the JavaScript data structure — a stack.

To quickly recap, remember that a stack is similar to a queue. Stacks are another type of list with a “Last In, First Out” (LIFO) principle. This means that the last element to be added to the list (or, in this case, the stack) will be the first one to be removed/returned. The first element to be added to the list will be the very last element to be removed/returned.

Stacks, similar to queues, also have three main operations: inserting an element at the end of the list (push), removing an element at the end of the list (pop), and returning the last element of the list (peek).

Today, I will be discussing how to implement a stack with an array. I will also go over the basics of the three main operations listed above.

Implementing a Stack (w/ an Array)

To implement a stack, we will be using an array.

class Stack {
constructor() {
this.items = []
}
}
var newStack = new Stack();
console.log(newStack); //=> []

Push/Pop

Next, to add and remove elements from a stack, all we need to use are the array methods, push and pop, accordingly. You could rename them for your own purposes, but because the names are already pretty self-explanatory, there is no need!

The push function will push an element to the end of the stack, and it will take in a parameter of whatever you will be added to the end of the stack. The pop function will pop off the element from the end of the stack, but it will not take in any parameters (because it will automatically look at the last element of the stack).

newStack.push('first');
console.log(newStack); //=> ['first']
newStack.push('second');
newStack.push('third');
console.log(newStack); //=> ['first', 'second', 'third']
newStack.pop();
console.log(newStack); //=> ['first', 'second']

Peek

To return the last (or top most) element of a stack without modifying it, we can create a function called peek.

class Stack {
... peek() {
if (this.items.length === 0) {
return "Stack is empty"
}
return this.items[items.length - 1];
}
}

Here, we check to see if the stack is empty or not. If it is empty, then we return a message saying that the stack is empty. If it’s not empty, then we simply grab the length of the stack (# of items in the stack) and subtract 1 to find the index of the last/top most element of the stack.

And there we have it! The stack is super similar to a queue — with the main difference being that the last element of a list is removed first in a stack, while the first element of a list is removed first in a queue.

--

--

Esther 승연 Kang

Software Engineer | Flatiron School Alum | Dancer | Looking for Work!