You type three sentences, then press Ctrl+Z. The sentence that disappears is the last one, not the first. Press it again, and the second sentence disappears. So whatever was done last is undone first.
This order is called LIFO, short for Last In, First Out: the last thing in is the first thing out. A data structure that works by the LIFO rule is called a stack. You can only add items to a stack and take them from it at one end: the top. A stack works like a stack of plates: a new plate goes on top, and the plate you take is also the top one.
A stack from a plain array
The end of the array counts as the top of the stack. The array stack starts as ["A", "B"], so A is at the bottom and B is on top:
| Step | Code | Result | Stack (bottom to top) |
|---|---|---|---|
| 1 | stack.push("C") |
C goes on top | A, B, C |
| 2 | stack.at(-1) |
"C", only looked at |
A, B, C |
| 3 | stack.pop() |
"C" |
A, B |
| 4 | stack.pop() |
"B" |
A |
| 5 | stack.pop() |
"A" |
empty |
This is the code, plus one more pop() when the stack is already empty:
const stack = ["A", "B"]; // bottom to top
stack.push("C"); // ["A", "B", "C"]
console.log(stack.at(-1)); // C (only looked at)
console.log(stack.pop()); // C
console.log(stack.pop()); // B
console.log(stack.pop()); // A
console.log(stack.pop()); // undefined, already empty
push("C")puts a new item on top, which is the end of the array.pop()takes the top item: the item leaves the stack and becomes the result ofpop().at(-1)only looks at the top item without taking it (-1means the last item of the array). This operation is called peek (a quick look). It gives the same asstack[stack.length - 1].pop()on an empty stack returnsundefined, not an error.
The items come out in the reverse of the order they went in: C, B, A.
Push, pop and peek are all O(1): the number of steps stays the same, however tall the stack is. The reason is that only the top is touched and no item has to move.
Wrapping it in a Stack class
A plain array can still be changed in ways that break LIFO, for example with shift(). To protect the LIFO rule, the array is wrapped inside a class that offers only push, pop and peek. A class is a blueprint for making objects. new Stack() makes one new stack. At that moment constructor (the part of the class that sets up the starting values) runs once. this means the stack in use, so this.items is that stack's own array.
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop(); // undefined when empty
}
peek() {
return this.items[this.items.length - 1];
}
}
const s = new Stack();
s.push("A");
s.push("B");
console.log(s.peek()); // B
console.log(s.pop()); // B
console.log(s.pop()); // A
- Inside the class, the array is always written
this.items, never justitems. A function inside a class is called a method. Thepushandpopmethods ofStackjust callpushandpopof the arraythis.items. peek()reads the last item without changing anything. So apop()right after it still gets the same item: B.- Two more methods you'll often see:
size()returns how many items there are (this.items.length), andisEmpty()returnstruewhenthis.items.length === 0.
Stacks are used in many places: the undo button, the browser's Back button, checking matching brackets like ({[]}), and the call stack (JavaScript's record of which function is running now).
💡 Why is a stack right for checking brackets? Every closing bracket has to match the last opening bracket that is not closed yet. In
({[]}),]must match[first, and only then}matches{. How it works: store every opening bracket withpush. Each time you find a closing bracket, take the top opening bracket withpop, then check that the two match. That's LIFO.
⚠️ A stack that takes the wrong item, or crashes
- Using
shift()as pop.shift()takes from the front of the array, so the item that comes out is the first one in. Besides the wrong order,shift()also moves every other item, so it's O(n). Add at the end withpush, and take from the end too, withpop(). - A peek that takes too. If
peek()callspop(), the stack loses an item without you noticing. Peek only reads. - Forgetting
this. Writingitems.push(item)inside the class causes an error, because there is no variableitems. Writethis.items. - Stack overflow. A function that keeps calling itself without stopping fills the call stack until there is no more room (an overflow), and then the error
Maximum call stack size exceededappears.
TL;DR: A stack is a LIFO data structure (Last In, First Out): the last item in is the first one out, like a stack of plates. push puts an item on top, pop() takes the top item, and peek only looks at the top item without taking it. All three are O(1), because only the top is touched. When a stack is made from an array, its top is the end of the array, and peek is written at(-1) or, for an array named items, items[items.length - 1]. Pushing A, B, C and then popping three times gives C, B, A. In a Stack class (a blueprint for objects), the items are kept in the array this.items: size() is this.items.length, isEmpty() is this.items.length === 0, and pop() on an empty stack returns undefined.
⚡ Last in, first out
Write:
const stack = ["A", "B"]; // bottom to top
stack.push("C"); // ["A", "B", "C"]
console.log(stack.pop()); // C
console.log(stack.pop()); // B
console.log(stack.pop()); // A
Guess first: why does C come out first, when A went in first?
Because this array is used as a stack. The rule of a stack is LIFO, Last In, First Out: the last item in is the first one out. Like a stack of plates: the plate put on last is on top, so it's taken first.
Meaning: The end of the array counts as the top of the stack. push puts an item on top, and pop() takes the top item. On an empty stack, pop() returns undefined, not an error.
⚡ peek only looks
Write:
const s = new Stack();
s.push("A");
s.push("B");
console.log(s.peek()); // B
console.log(s.pop()); // B
Meaning: Stack is a class (a blueprint for objects) that keeps its items in an array, and new Stack() makes one new stack. peek() looks at the top item without taking it, so a pop() right after it still gets the same item: B. On a plain array, peek is written at(-1) (the last item) or stack[stack.length - 1]. Push, pop and peek are all O(1), because only the top is touched.
⚡ Don't use shift() as pop
Guess first: shift() takes the first item of an array. If you take items from a stack with shift(), which item comes out?
The first item in, because that item is at the front of the array. The order is wrong. shift() also moves every other item, so it takes as many steps as there are items: O(n).
Meaning: Add at the end of the array with push, and take from the end too, with pop(). Inside the Stack class, the array is written this.items (this means the stack in use). Two more functions a stack class often has: size() counts the items with this.items.length, and isEmpty() checks whether the stack is empty with this.items.length === 0.