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 | class Stack { |
In this implementation, we have five public methods:
push()
andpop()
to add and remove items from the stackisEmpty()
to check if the stack is emptyempty()
to clear the stacksize()
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 | const stack = new Stack() |
Alternatively, you can make the items
property public by removing the private class field syntax:
1 | class Stack { |
With this change, you can inspect the items
array from the outside:
1 | const stack = new Stack() |
However, with private class fields, accessing stack.items
would return undefined
, providing better encapsulation of the stack’s internal state.