Imperative vs declarative programming: Differences, pros and cons
Contents
Declarative vs imperative programming comes down to how versus what: imperative code spells out the steps and manages state and control flow itself, while declarative code describes the result and lets a framework, query engine or runtime choose the steps. Declarative programming is therefore a style where you state the desired outcome, as in SQL or a React component.
In UI work the split decides who keeps the screen in sync with state. The right choice depends on how much control and predictable cost the code needs against how much synchronization it can afford to write by hand.
Declarative vs imperative programming: The short answer
Declarative vs imperative comes down to who owns the steps: imperative code says how, declarative code states the result and lets the runtime decide how. Declarative UI applies this to screens, treating UI as a function of state, as React does, which targets the drift that appears when two handlers mutate the same node.
Netguru builds web and mobile products with declarative UI frameworks such as React, SwiftUI, Jetpack Compose and Flutter, alongside native imperative code.
We recommend declarative as the default for screens and queries in web development projects, because it cuts synchronization code, and imperative for animation, focus and canvas work, where the exact steps matter.
What are imperative and declarative programming?
Imperative programming specifies how to reach a result through ordered steps and explicit state changes. Declarative programming specifies the result and leaves the steps to an engine, such as a query optimizer or a UI framework.
ALGOL introduced structured programming in the 1960s, and C gave systems code direct control over execution order and memory in the 1970s.
The task "names of active users" shows where ownership shifts. The imperative loop exposes control flow and mutable state:
const activeNames = [];
for (let i = 0; i < users.length; i++) {
if (users[i].active) {
activeNames.push(users[i].name);
}
}
The declarative version states the result with filter and map:
const activeNames = users
.filter(u => u.active)
.map(u => u.name);
SQL goes one step further, because the query never says how to scan:
SELECT name FROM users WHERE active = true;
| Version | Who owns iteration | Who owns state | Can execution change without editing the code? |
|---|---|---|---|
| JavaScript loop | You (index, branch, push) | You (the mutable array) | No |
| map/filter | The runtime, in a fixed order | The runtime builds a new array | No, the order is fixed |
| SQL | The database | The database | Yes, for example when an index is added |
In SQL, the PostgreSQL planner picks the execution path from the available indexes and statistics, so the same query can run differently as the data grows. map and filter offer no such choice. Their benefit is fewer places to get state wrong.
Our rule of thumb for choosing between the first two versions depends on what the loop body does:
- Use map/filter when the body only selects or transforms items and nothing else depends on the loop's side effects.
- Keep the loop when you need an early exit, several accumulators in one pass, or a guaranteed order of side effects.
- Use SQL when the data already lives in a database and the engine can use its indexes.
Where do you see each style in practice?
Declarative programming shows up in SQL, HTML and CSS, regular expressions, Terraform, and functional-style code. C and Java are mostly written step by step, and Python mixes both. The table compares what you write in each, what the engine decides, and where imperative behavior leaks back in.
| Language or tool | Dominant style | You write | The engine decides | Where imperative detail leaks in |
|---|---|---|---|---|
| SQL | Declarative | The result set you want | Join order and index use, via the query optimizer | Vendor procedural extensions, query hints |
| HTML and CSS | Declarative | Structure and appearance | Layout and painting | JavaScript that manipulates the DOM |
| Regular expressions | Declarative | A pattern to match | How the matcher searches the input | In backtracking engines, pattern shape affects run time |
| Terraform | Declarative | The desired infrastructure state | The create, update, and destroy calls needed | Provisioners that run scripts |
| Functional style (map, filter, Haskell) | Declarative style | Expressions that transform data | How iteration and evaluation proceed | Callbacks with side effects |
| C | Imperative | Ordered steps, explicit mutation | Little beyond executing your instructions | Not applicable |
| Java | Imperative, multi-paradigm | Classes, loops, and stream pipelines | Iteration inside a stream | Mutation inside lambdas |
| Python | Multi-paradigm, imperative by default | Loops and assignments, or comprehensions | Little; comprehensions still run in order | Any comprehension body that mutates state |
Terraform compares your configuration with its recorded state and produces a plan of changes before anything is applied (HashiCorp Developer: Create a Terraform plan, 2024).
How to read the table
Two patterns show up. Tools where the engine owns execution order (SQL, CSS, Terraform) are declarative at the top and imperative underneath, because the optimizer, renderer, or provider is itself step-by-step code.
Languages where you own execution order (C, Java, Python) let you borrow a declarative style locally. JavaScript and C# follow the same split as Java streams and Python comprehensions.
Our rule of thumb: a snippet is declarative to the extent that you could swap the engine's strategy without editing your code. A SQL query passes that test. A Python comprehension mostly does not, so call it declarative in style only.
Is Python imperative or declarative?
Python is a multi-paradigm language that is imperative by default: statement-level control flow, assignment, and mutable objects push most code toward step-by-step instructions. Its Functional Programming HOWTO documents comprehensions, generators, itertools, and functools as the toolkit for a more declarative style.
We recommend treating Python as imperative and using comprehensions and itertools as local declarative islands. Reach for a comprehension when you build one collection from another with no side effects. Keep a for loop when the body mutates state, writes several outputs, exits early, or handles exceptions.
A comprehension states the result you want, but the interpreter still runs it in order, and Python has no query optimizer to reorder work the way a SQL engine does. Judge each island by whether a reviewer can read it in one pass.
What changes with declarative UI?
Declarative UI changes who owns synchronization: you describe the interface as a function of state, and the framework updates the screen when that state changes.
In UIKit, Android Views, and direct DOM manipulation, your handlers hold the state and also patch every node that displays it. React, SwiftUI, Jetpack Compose, and Flutter invert that arrangement. You write UI as a function of state, and the framework reconciles, recomposes, or rebuilds the affected parts.
Here is one cart component written both ways:
// Imperative: the handler patches every affected node
function addItem(item) {
list.append(Object.assign(document.createElement("li"), { textContent: item.name }));
badge.textContent = list.children.length;
empty.hidden = true;
}
// Declarative: the component returns UI for the current state
const Cart = ({ items }) => items.length === 0 ? <p>Empty</p> :
<ul>{items.map(i => <li key={i.id}>{i.name}</li>)}</ul>;
The imperative handler touches three nodes. A matching removeItem must reverse all three, including restoring the empty message when the last item goes. Each new handler is another place where the screen can drift from the data.
The declarative component has no such handler. An event updates the items array, and the framework re-evaluates the function, which is why the React docs tell you to describe each visual state instead of scripting transitions between them. Jetpack Compose and Flutter document the same model for their toolkits.
You take on a different job in return. Render code has to stay free of side effects, list keys have to be stable, and state has to live at the right level. State hoisting and memoization are how you control re-renders and recomposition. Hooks such as useState are how React components hold that state, and React hooks examples shows them in use.
For native mobile teams, we recommend migrating a UIKit or Android Views codebase one screen at a time. SwiftUI and Compose both interoperate with the older toolkits, so the two models can coexist during the move, and our mobile development services cover that kind of incremental migration.
Imperative programming pros
Imperative programming pros start with direct control flow: in UIKit and Android Views, you decide which view changes, when it changes, and what each change costs.
A form field that needs to shake, a list row that animates out, a focus ring that moves after validation: each is one explicit call on a known object. Direct DOM manipulation on a web development project works the same way, with a targeted update touching one node.
Per-operation cost is predictable. Setting the text on a UILabel in UIKit changes one property on one object, with no diffing, reconciliation, or recomposition pass between the call and the screen, so scroll handlers, gesture tracking, and custom drawing benefit from a frame budget that leaves room for only the work you can inspect.
Three further advantages follow from the same control:
- Hot-path access: you can pool and reuse views, batch writes, and order operations by hand. C earned its place in systems code through this kind of control over memory and system resources.
- Debugging: a stack trace usually ends at the line that mutated the view, so you step through your own code and not framework internals.
- Familiarity: most developers learned this style first, so a new hire needs no new mental model.
The cost is synchronization code that you write and maintain yourself. On a screen with a handful of states, that overhead stays small. We recommend keeping imperative code for animation, custom drawing, and input handling, even inside an otherwise declarative app.
Imperative programming cons
Imperative programming cons show up first in UI code, where direct DOM manipulation and mutable state let any handler change a node without the others knowing. The cost grows with the number of writers per node, not with the size of the codebase.
Two handlers, one badge:
const badge = document.querySelector("#cart-badge");
addButton.addEventListener("click", () => {
badge.textContent = Number(badge.textContent) + 1;
badge.hidden = false;
});
clearButton.addEventListener("click", () => {
badge.textContent = "0";
});
After a clear, the badge shows "0" and stays visible, because only the add handler knows about hidden. The node doubles as the data store: the add handler reads the count back from the screen, so any other writer silently changes its input. Each new handler multiplies the combinations to check.
Android Views has the same failure. setText and setVisibility calls scatter across click listeners, observers, and fragment callbacks, and the view ends up in a state no single function describes.
We suggest treating these as early signs:
- A bug that reproduces only in one event order, such as clear before a late network response.
- The same selector or view ID written from more than one file.
- Code that reads values back from a view to decide what to do next.
- Fixes that add another conditional to one handler instead of removing a writer.
Once a node has three or more writers, a single render function that derives the whole view from one state object is usually cheaper than another patch.
Declarative programming pros
Declarative UI makes screens predictable: SwiftUI, Jetpack Compose, and React render from current state, so a wrong screen traces to one state value, not to the order in which handlers ran. The React docs frame the work as describing each visual state and letting the framework move between them.
Three gains follow in UI code:
- Less synchronization code. A cart badge becomes one expression of the item count. No click handler writes to the node, so adding a third way to change the cart touches no display logic.
- Easier testing. A render function that takes state and returns a view tree can be checked against a table of states with no browser or simulator. With state hoisting in Compose, composables receive fixed inputs in previews and tests.
- Reviewable diffs. A change reads as a new state-to-view mapping, which a reviewer can check without simulating event order in their head.
The same logic carries beyond UI. A Terraform configuration declares the infrastructure you want, and terraform plan compares it with recorded state before anything changes. Applying a configuration that already matches reality should change nothing, which makes re-runs safe in CI.
SQL gives query authors a similar deal. You state the result, and the PostgreSQL planner picks join order and index use, so adding an index can speed up a query without editing it.
These gains depend on the runtime doing its part. For a UIKit or Android Views codebase, adopting SwiftUI or Compose screen by screen is the usual path, and mobile development work typically runs both side by side during the move. For a single small widget or a one-off script, the framework setup can cost more than the loop it replaces.
Declarative programming cons
Declarative programming trades control for convenience: the framework decides when work happens, so performance, debugging, and focus or animation handling depend on its rules.
Performance problems start with inputs the framework cannot prove unchanged. In React, a new object, array, or function created on every render defeats memoization, and virtual DOM reconciliation then diffs subtrees that did not change.
Jetpack Compose has the same failure in recomposition: an unstable class parameter or a freshly allocated lambda forces child composables to rerun. SwiftUI and Flutter rebuild view bodies and widgets in a similar way when state sits too high in the tree.
Holding state too high reruns large subtrees on every change, while placing it too low pushes you to copy values between components, which brings back the synchronization code declarative UI was meant to remove. This is the second failure mode.
Debugging also moves inside the framework. A stack trace passes through the reconciler or the Compose runtime, and a symptom like typed input jumping to the wrong list row (often from index-based keys in React) only makes sense if you know the diffing rules.
Genuine reconciler bugs exist, but in our view misreading those rules is the more likely cause, which is why the learning curve is a real cost.
Every mature framework ships an escape hatch back to imperative code, and each one makes you own a lifecycle:
| Framework | Escape hatch | What you take on |
|---|---|---|
| React | Refs and effects | Syncing the imperative call with state and cleaning up after it |
| SwiftUI | UIViewRepresentable wrapping a UIKit view | Keeping the wrapped view and SwiftUI state consistent |
| Jetpack Compose | AndroidView interop, Canvas drawing | Updating Views or draw calls from state without leaks |
| Flutter | CustomPainter, platform views | Repaint rules and native view lifecycle |
A typical React case is moving focus, which the render output cannot express:
function Field({ focused }) {
const ref = useRef(null);
useEffect(() => {
if (focused) ref.current.focus();
}, [focused]);
return <input ref={ref} />;
}
Keep these hatches small and wrapped in one component. For most screens the abstraction cost is negligible, so we recommend profiling before restructuring state or adding memoization.
Imperative vs declarative: Comparison table
Imperative and declarative code differ most in who owns the steps: you write them in imperative code, and the runtime derives them in declarative code. The table extends the usual how-versus-what split to debugging, testing, and tooling.
| Aspect | Imperative | Declarative |
|---|---|---|
| Focus | How: the ordered steps to reach a result | What: the result or end state you want |
| Control flow | Loops, branches, and calls you sequence yourself | Owned by the engine: the SQL query optimizer picks the plan, React reconciliation picks the DOM updates |
| State | Mutated in place; you keep the screen in sync by hand | Derived from inputs, so the UI is a function of state |
| Abstraction | Close to the machine's operations | Higher level; the runtime hides the steps |
| Debugging | Breakpoints and stepping follow your code in order | Inspect inputs and outputs, then use engine tools such as EXPLAIN, React DevTools, or terraform plan |
| Testing | Assert on side effects and intermediate state | Assert on output for a given input; tends to need fewer mocks |
| Typical tools | UIKit, Android Views, direct DOM calls, C, Java | SQL, React, SwiftUI, Terraform, HTML and CSS |
Treat the cells as tendencies. A UIKit screen can be tested well, and a React component full of effects is still debugged step by step. A practical starting point is refactoring small, isolated pieces, such as a loop that builds a list, into map and filter or a React component, before touching architecture.
Declarative vs imperative IaC: Terraform and the difference
Declarative infrastructure as code states the end state you want, and Terraform computes the changes to reach it; an imperative script lists steps and runs them in order.
The difference shows on the second run. A re-run script repeats its steps blindly, and unless the author wrote an existence check for each one, it creates duplicates or fails halfway. Terraform's plan command compares configuration with recorded state and refreshed real resources, then lists only the differences. That comparison is how it detects drift.
Kubernetes follows the same split. A manifest declares the image and replica count, and controllers keep reconciling the cluster toward it. An imperative command, such as scaling a deployment by hand, changes the cluster once and records no intent, so the next apply of the manifest can reverse it.
A plan has limits. It sees only resources in its state, so a firewall rule added by hand in a console stays invisible until you import it. It shows what will change, not whether the result works, and generated values stay unknown until apply. Because the world can move between plan and apply, we recommend applying a saved plan file from CI.
When should you choose each?
Choose declarative code when a framework or engine can own the steps for you, and imperative code when you must control the order, timing, or memory yourself. The scenarios below each carry one deciding condition.
| Scenario | Choose | Rule |
|---|---|---|
| Application screens | Declarative UI (React, SwiftUI, Jetpack Compose, Flutter) | If more than one event can change the same element, describe the screen as a function of state. |
| Reporting and analytics queries | SQL | If the question is about sets of rows, state the result and let the query optimizer pick join order and indexes. |
| Cloud environments | Terraform | If the environment must be reproducible and reviewable, declare the end state and read the plan before applying. |
| Firmware, drivers, device code | Imperative | If correctness depends on exact control flow, register writes, or interrupt timing, write every step. |
| Measured hot paths | Imperative, locally | If a profiler shows the abstraction's cost on one path, rewrite that path by hand and leave the rest alone. |
For the infrastructure row, a Terraform plan lets reviewers see a diff before anything changes. A step-by-step script offers no such preview unless you build one.
These rules assume the team already knows the framework. On a small prototype, a few lines of direct DOM code can cost less than adopting a UI library.
Mixed codebases are the norm. A SwiftUI screen still calls imperative networking code, and a Terraform module sometimes ships a last-resort provisioner when a resource has no provider support. Keep that imperative code behind a narrow interface so the declarative layer stays readable.
How do real codebases mix both?
Real codebases mix both by wrapping imperative internals in a declarative shell. React or SwiftUI views describe the declarative UI as a function of state, while mutable state, I/O, and timing live in step-by-step code underneath.

Side effects sit at the boundary. In React, effects and refs hold the imperative calls that focus an input, drive a canvas, or open a subscription. SwiftUI offers .task for async work and UIViewRepresentable to wrap a UIKit view. Keeping the render path pure makes the imperative code easy to find.
We recommend this order when moving an imperative codebase:
- Convert small, isolated pieces first, such as one widget or one data transformation, into a declarative form: a map/filter pipeline or a component that takes props.
- Move each piece of mutable state to the nearest common parent, so every value has one writer.
- Wrap each remaining imperative call (animation, focus, third-party widgets) in a single effect or adapter.
- Profile before dropping down to imperative control.
Re-render and recomposition problems often yield to memoization or better state placement. Direct control is worth its cost only when a profile shows the framework's rules are the bottleneck. Framework choice changes where these boundaries sit, and our React vs Angular comparison covers that.
FAQ
What is imperative and declarative in Kubernetes?
What is declarative programming?
What is the difference between declarative and imperative programming?
Is SQL declarative or imperative?
Is functional programming declarative?
Default to declarative, drop down deliberately
Default to declarative UI in new work, and drop to imperative code only where the framework's model runs out.
React, SwiftUI, Jetpack Compose, and Flutter all treat the screen as a function of state, which removes most of the synchronization bugs that hand-written DOM or UIKit updates produce.
Drop down deliberately for animation timing, focus management, canvas drawing, and profiled hot paths. Keep that code behind a small interface so the rest of the tree stays declarative. Queries and infrastructure follow the same rule: write SQL and Terraform configuration for the result you want, and use procedural code when the planner or provider can't express the step.
If you're weighing a stack choice or a migration from UIKit or Android Views, talk to our team and we'll help you scope it.
