🤔 What’s the difference?

At its core, the difference between imperative and declarative code is:

Imperative: How to do somethingDeclarative: What you want to happen

It’s a shift from control flow to intent.


📣 Imperative code

Imperative code describes step-by-step how to achieve a result. You manually control the state and flow.

Example: sum of even numbers (IMPERATIVE)

const numbers = [1, 2, 3, 4, 5, 6];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    sum += numbers[i];
  }
}
console.log(sum); // 12
  • Verbose
  • Lots of control logic (for, if, i)
  • Focuses on how the result is built

🌿 Declarative code

Declarative code expresses the result you want, and lets the system handle the steps.

Same example (DECLARATIVE)

const numbers = [1, 2, 3, 4, 5, 6];
const sum = numbers.filter(n => n % 2 === 0).reduce((acc, n) => acc + n, 0);

console.log(sum); // 12
  • Cleaner and shorter
  • Focuses on what the outcome is
  • Uses higher-order functions

🧠 Real-world analogy

  • Imperative: Writing down exact driving directions.
  • Declarative: Saying “take me to the airport” in an Uber.

🔍 More examples

Updating DOM elements

Imperative (Vanilla JS):

const el = document.createElement('div');
el.textContent = 'Hello';
el.style.color = 'red';
document.body.appendChild(el);

Declarative (React JSX):

function App() {
  return <div style={{ color: 'red' }}>Hello</div>;
}

React describes the UI and figures out DOM updates for you.


SQL Is declarative

SELECT name FROM users WHERE age > 18;

You’re saying what data you want — not how to scan the tables.


📦 Declarative libraries in javascript

PurposeImperative StyleDeclarative Alternative
DOM ManipulationVanilla JSReact
StatesetState() chainsZustand, Redux Toolkit
RoutingManual listenersReact Router
Styleselement.styleTailwind, Styled Components
Animationsmanual CSS/JSFramer Motion

🧪 When to use each

Use CasePrefer
Performance-critical, low-level logicImperative
UI, state transformations, logic clarityDeclarative
Algorithms (sorting, traversal)Often Imperative
UIs, rules, filters, configDeclarative

⚖️ Pros and cons

Imperative Pros:

  • More control
  • Useful for complex state machines, algorithms

Imperative Cons:

  • Verbose
  • Easy to introduce bugs through state mutations

Declarative Pros:

  • Readable, abstract
  • Easier to maintain and test

Declarative Cons:

  • Less control
  • May hide performance costs

🧵 Final thoughts

Declarative code is not better than imperative — it's a tool to express intent clearly. In modern frontend development, especially with frameworks like React, declarative thinking leads to cleaner, more maintainable code.

Write declaratively when expressing what, and imperatively when optimizing how.