Imperative vs Declarative programming

Imperative – How you do

I’m going to go to the shop, walk through the door, take a right, go to isle 19, on the bottom shelf I’m going to pick up a loaf of bread, head to the till and pay.

Declarative – What you do

I’m off to get some bread.

What in the metaphor do this mean?!

Imperatitive

Let’s look at a code example of imperative programming

var el = document.createElement("div");
el.innerHTML = "Some content inside our div";
document.getElementById("root").appendChild(el);

In the above example, we explicitly create our element, change the text and then append that to our root ID. We’re telling the machine how we’re going to do something (you can think of it as steps to accomplish a task).

Declarative

Now let’s look at a declarative code example.

<div>Some content inside our div</div>

A simple HTML line can be used here. We don’t necessarily care about the exact step by step, we just want to a div with some content how the machine solves this doesn’t matter to us.