/

The Stack Data Structure in JavaScript: Explained and Implemented

The Stack Data Structure in JavaScript: Explained and Implemented

tags: [“JavaScript”, “data structure”, “stack”]

A stack is a data structure that comes with certain limitations, contrasting it with arrays. In a stack, we can only add items on top and remove the top item. Think of it like a pile of books, where you can only add books to the top and remove the one on top. This behavior is known as First In, Last Out (FILO).

While arrays in JavaScript are already built-in and readily available, we still need to implement stacks ourselves. To do this, we can create a data structure that encapsulates the data and allows limited access. We will only allow the use of the push() method to add data to the stack and the pop() method to remove data from the stack.

There are different ways to implement stacks, and one approach is using classes. In particular, we can utilize private class fields. Although private class fields are not yet part of the JavaScript standard, they are available in Chrome, Edge, Safari, and Node.js (v12 and above). Unfortunately, they are not yet supported in Firefox, but hopefully, this will change soon.

Private class fields are helpful because they easily allow us to encapsulate the internal state of the class and protect it from external access. Here’s an example implementation using private class fields:

1
2
3
4
5
6
7
8
9
class Stack {
#items = []

push = (element) => this.#items.push(element)
pop = () => this.#items.pop()
isEmpty = () => this.#items.length === 0
empty = () => (this.#items.length = 0)
size = () => this.#items.length
}

In this implementation, we have five public methods:

  • push() and pop() to add and remove items from the stack
  • isEmpty() to check if the stack is empty
  • empty() to clear the stack
  • size() to get the current size of the stack

To use this stack implementation, you can create a stack object from the class and interact with it:

1
2
3
4
5
6
7
const stack = new Stack()
stack.push(1)
stack.push(2)
stack.push(3)
console.log(stack.size()) // Output: 3
console.log(stack.pop()) // Output: 3
console.log(stack.size()) // Output: 2

Alternatively, you can make the items property public by removing the private class field syntax:

1
2
3
4
5
class Stack {
items = []

// Rest of the code...
}

With this change, you can inspect the items array from the outside:

1
2
3
const stack = new Stack()
stack.push(2)
console.log(stack.items) // Output: [2]

However, with private class fields, accessing stack.items would return undefined, providing better encapsulation of the stack’s internal state.