Member-only story
This is the second in a series on data structures re-implemented in Javascript. We’re going to look at the Stack structure. The stack is critical in computer science because the stack data structure is actually used extensively by the programming language itself. Every method or function call you make in javascript is placed on a stack (referred to as THE stack) which the language runtime uses to manage program execution.
What is a stack?
If you’ve ever stacked books, you know how a stack works. The first book goes on the bottom and then each subsequent book goes on top. If you want to remove a book from the middle of the pile, you would first need to move all the books above it.
This arrangement, in which the only item you can freely move without moving anything else is a LIFO Stack. LIFO means “Last In, First Out”.
In Javascript, we could implement stack functionality using the built-in Array object and the push and pop methods, but this would hide what is really going on. The whole point is to understand the data structure from the very foundation. No helpers. We’re going to instead implement this in a raw fashion.
class Stack {
constructor() {
this._last = null;
this._length = 0;
} pop() {
const…