Stacks (LIFO)
A stack works like a pile of plates: you add to the top and take from the top. The last item in is the first out — LIFO. The two operations are push (add) and pop (remove the most recent).
class Stack {
constructor() { this.items = [] }
push(x) { this.items.push(x) }
pop() { return this.items.pop() }
peek() { return this.items[this.items.length - 1] }
get size() { return this.items.length }
}
Edit and run this — it uses a stack to reverse a word:
Try it yourself
Loading editor…
Undo in an editor, the browser Back button, and the call stack that runs your functions are all stacks.