- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Stacks in JavaScript
Stacks and Queues
Stacks in JavaScript
A stack is an array where you agree only to touch the end. That restriction is the whole value - it makes the structure O(1) at everything it does, and it makes certain problems obvious.
Last in, first out
You add to the top and remove from the top. The last thing in is the first thing out, like a stack of plates.
In JavaScript you do not need a class. An array with only push and pop is a stack, and both are O(1) because nothing else moves.
A stack, and a stack with a name
javascript
// Perfectly good stack.
const stack = []
stack.push(1)
stack.push(2)
stack.pop() // 2
stack[stack.length - 1] // peek at the top
// The same thing, when clarity matters more than brevity.
class Stack {
#items = []
push(value) { this.#items.push(value) }
pop() { return this.#items.pop() }
peek() { return this.#items[this.#items.length - 1] }
get size() { return this.#items.length }
get isEmpty() { return this.#items.length === 0 }
}