Declarative vs Imperative at Five Levels

1. Child:

Imagine you’re building with blocks. An imperative way to do it would be like someone telling you “Pick up a red block. Now place it on the table. Now pick up a blue block. Now place it on top of the red block”. Declarative is more like if someone shows you a picture of what the finished tower of blocks should look like and says “Make it look like this.” You don’t need to be told each step, you can see what the end goal is.

2. Teenager:

Suppose you’re playing a video game with a friend. Imperative programming is like telling your friend exactly what buttons to press at each step. “Press X, now press right arrow, now press down arrow”. Declarative programming is like telling your friend the overall strategy for winning. “Try to corner the enemy, watch out for their special attacks, keep your health high”. You’re not telling them every detail, but you’re giving them the big picture of what they should be trying to do.

3. College student (not a CS major):

Imagine you’re writing a paper. Imperative writing is like a detailed outline where you specify every point you’re going to make in order. “First I’ll write about A, then I’ll write about B, then I’ll write about C”. Declarative writing is like a thesis statement or abstract. “This paper argues that X because of Y and Z”. You’re stating the overall goal or effect of the paper without specifying every step that will get you there.

4. Computer Science Undergraduate:

In programming, imperative code tells the computer what steps to take to solve a problem. This often involves specifying control flow using statements like if, for, while, etc. Declarative code, on the other hand, describes the desired result without explicitly listing out the steps to get there. SQL, for example, is a declarative language: you describe what data you want, not how to retrieve it.

5. Grad student/Colleague:

Imperative programming involves coding with explicit commands, controlling the flow with statements, loops, and conditionals. It focuses on how to achieve results. On the other hand, declarative programming abstracts the control flow and focuses on what to achieve, describing the desired results without explicitly listing out the steps to get there.

Functional programming languages like Haskell are often more declarative, while languages like Java or C tend to be more imperative. JavaScript, however, supports both styles. The rise of libraries and frameworks like React has led to more widespread use of declarative styles in JavaScript for certain tasks, like UI development.