How to Create a Stack Data Structure in JavaScript
Building a simple stack class in JavaScript with private fields.
There are times when you need to keep track of things in order and always deal with the most recent one first. Undo in a text editor, the browser's back button and the JavaScript call stack all work this way. The data structure behind all of them is a stack.
A stack is a LIFO (last in, first out) data structure. The last item added is the first item removed.
Think of a stack of plates. You add a plate to the top and you take a plate off the top. You never pull one out of the middle.
Using an Array as a Stack
JavaScript doesn't have a built-in stack, but arrays already have the two
methods you need. push adds an item to the end and pop removes the item at
the end:
const stack = []stack.push("a")stack.push("b")stack.push("c")console.log(stack.pop()) // "c"console.log(stack) // ["a", "b"]
This works fine for quick scripts. The downside is nothing stops someone from
calling stack.shift() or setting stack[0] directly, which breaks the whole
idea of a stack.
Building a Stack Class
Wrapping the array in a class lets you control exactly what can be done with it:
class Stack {#items = []push(item) {this.#items.push(item)}pop() {return this.#items.pop()}peek() {return this.#items[this.#items.length - 1]}isEmpty() {return this.#items.length === 0}size() {return this.#items.length}}
The #items field is a private class field. The # means it can only be
accessed from inside the class, so the only way to change the stack is through
its methods. Writing stack.#items anywhere outside the class is a
SyntaxError.
pushadds an item to the toppopremoves the top item and returns itpeekreturns the top item without removing itisEmptychecks if there's anything in the stacksizereturns how many items are in the stack
Using it looks like this:
const stack = new Stack()stack.push(1)stack.push(2)stack.push(3)stack.peek() // 3stack.pop() // 3stack.size() // 2stack.isEmpty() // false
Calling pop or peek on an empty stack returns undefined, the same as an
empty array would.
Try it below. The buttons call the same Stack class:
- 1
- 2
- 3
A Practical Example: Balanced Brackets
A classic use for a stack is checking if the brackets in a string are balanced. Every opening bracket gets pushed onto the stack, and every closing bracket has to match the one on top:
function isBalanced(str) {const stack = new Stack()const pairs = { ")": "(", "]": "[", "}": "{" }for (const char of str) {if (char === "(" || char === "[" || char === "{") {stack.push(char)} else if (pairs[char]) {if (stack.pop() !== pairs[char]) return false}}return stack.isEmpty()}isBalanced("{[()]}") // trueisBalanced("([)]") // falseisBalanced("((") // false
When a closing bracket shows up, pop takes the most recent opening bracket
off the stack and checks that it's the right pair. If it isn't, the string is
unbalanced. At the end the stack should be empty, otherwise there are opening
brackets that never got closed.
That's it. A stack is just a few lines of code, but it's the right tool any time the last thing in should be the first thing out.
Have some feedback on this post? .