Contents

Programming Fundamentals › Functional Programming

Declarative vs Imperative

Describing what you want vs spelling out how to do it.

Also known as: imperative programming, declarative programming

Imperative code spells out how to do something, step by step. Declarative code describes what you want, and leaves the how to the system.

# Imperative: how
result = []
for user in users:
    if user.active:
        result.append(user.name.upper())

# Declarative: what
result = [u.name.upper() for u in users if u.active]
SELECT name FROM users WHERE active = true;      -- say what you want; the database decides how

Where you meet each

DeclarativeImperative
SQL, HTML, CSSloops and assignments in most languages
React-style UI (describe the UI for this state)manually editing the DOM step by step
Terraform and Kubernetes manifests (the desired state)shell scripts that run commands in order
map / filter (map, filter, reduce)hand-written index loops
// declarative UI
{items.length ? <List items={items} /> : <Empty />}

Trade-offs

  • Declarative is usually shorter and easier to read, because it states intent. The system can optimize, and you avoid whole classes of bugs (forgot to update the screen).
  • Imperative gives control over exact steps and performance, and is easier to debug step by step.

It’s a spectrum, not a switch. Real programs mix them. A good habit is to write at the most declarative level that stays clear, and drop to imperative when you need control. See functional programming for a style that leans declarative.