DSA Basics: Stack

Learn stack operations, LIFO behavior, common use cases, and implementation patterns.

Back to Learn DSA

A stack is a linear data structure where the last value added is the first value removed.

This rule is called LIFO, which means Last In, First Out.

Core operations

Mental model

Think of a stack as a pile of plates. You add a new plate on top, and you remove the top plate first.

top
  9
  5
  2
bottom

JavaScript implementation

class Stack {
	constructor() {
		this.items = [];
	}

	push(value) {
		this.items.push(value);
	}

	pop() {
		return this.items.pop();
	}

	peek() {
		return this.items[this.items.length - 1];
	}
}

Where stacks show up

Stacks are useful when the newest unfinished task must be handled first.

Complexity

Use the visualizer below to push and pop from the top.

Interactive walkthrough

Stack Visualizer

Push and pop values from the top of the stack.