Imperative vs Declarative Programming
Problem What is the difference between imperative and declarative programming?
Be ready to discuss
- Imperative: you spell out how to reach the result - explicit statements, control flow, loops, and mutation of state over time.
- Declarative: you state what result you want and leave the execution strategy to the underlying engine or runtime.
- Concrete pairs: a
forloop that pushes into an array vsmap/filter/reduce; hand-written traversal vs a SQL query the planner optimises. - Why declarative code enables optimisation: the engine is free to reorder, batch, parallelise, or cache because you never pinned down the steps.
- React as the canonical UI example: JSX declares the target state of the tree, and React's reconciler emits the imperative DOM mutations for you.
- Other declarative surfaces worth naming: SQL, HTML/CSS, Terraform, Kubernetes manifests, regular expressions.
- The trade-offs: declarative code is more concise and less bug-prone but leakier to debug and harder to performance-tune when the engine picks badly.
- Why the distinction is a spectrum, not a binary - most real code mixes both, and declarative layers are built on imperative ones.
asked …