Skip to main content

Stack

What a stack is, why LIFO order shows up so often, and when push/pop is already the right mental model.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

A stack is a LIFO structure:

last in, first out.

The most recent item is the first one to come back out.

In JavaScript

The simplest version uses an array with push and pop:

const stack: string[] = []

stack.push('(')
stack.pop()

When to use it

It usually fits when the problem asks you to:

  • undo the most recent step
  • close something that was opened before
  • keep temporary context

Better question

Instead of memorizing the name, ask:

  1. does the most recently opened item need to be handled first?
  2. is there a natural undo order here?
  3. do I need short, reversible history?

Keep exploring