DEV Community

loading...
Cover image for What Is the Difference between Imperative and Declarative Code

What Is the Difference between Imperative and Declarative Code

reedbarger profile image Reed Barger Originally published at reedbarger.com Updated on ・4 min read

What manner of coding should you strive for in your day-to-day work?

It's a question that's not asked often in programming, but it's an important one.

Let's first talk about a coding style you want to avoid throughout your programming career, whether you are just writing code for yourself or for others.

What is imperative and declarative code?

We can categorize how we write code as leaning towards one of two styles.

To be clear, a person's code never strictly falls into one category or another, but it is a useful way of referring to the manner in which we code, according to whom or what it is best suited.

Written code is referred to as imperative or declarative. These are complex-sounding words for ultimately simple concepts:

Imperative code is when we write code more suitable for a computer and declarative code is that is more readable for a person.

In more specific terms, imperative code is when we tell JavaScript (or whatever language in which you're coding) what to do and how to do it.

Imperative code and why you should avoid it

Imperative coding is a style that you should seek to avoid. Here's why—

Let’s say we had an array of people that we wanted to write an individual invitation to for our birthday party. Let's create our list of people.

Next, we want to store each written invitation as well, so let's create an invitations array for those to be put in.

const people = [Doug, Fred, Jane];
const invitations = [];
Enter fullscreen mode Exit fullscreen mode

As you might have already guessed, we need to iterate over this array to accomplish our goal. First, we're going to do in the way it needed to be done for most of JavaScript's lifetime: with a for-loop.

Here's how to write one:

for (let i = 0; i < people.length; i++) {
  invitations[i] = `Hi ${people[i]}, come to my party!`;
}
Enter fullscreen mode Exit fullscreen mode

According to the steps I mentioned, we want to loop (iterate) over an array, getting each element, a person's name, which we add to a message (the string above) and then adding it to a new array.

But does the code tell the same story?

If we were to read the code, we’re setting a variable i to 0, checking if it is less than the current length of the array, adding 1 to i, interpolating the ith value of the array to a string and putting it in the same index in a new array.

This is all imperative, we're telling JavaScript exactly what to do and how to do it. And all of this code is correct.

If we run it, we'll get all of our messages, just like we wanted.

However, your first intuition about this code (as with so many of us who look at a for-loop for the first time), may be that it doesn't look right.

That being said, it has undoubtedly been the most popular way to iterate over arrays over the course of the language's lifetime. Yet it's imperative and challenging to read and remember.

Declarative code and why write in a declarative style

What about if we wrote it in a declarative style, what would that look like?

Declarative code is different. As the name indicates, we declare with it what we want to accomplish, and JavaScript will do it—simple as that.

In other words, it is readable to us as humans and not just to the computer. In fact, its readability to other developers what we are pursuing in attempting to write in a more declarative style.

So let's rewrite our code in a style you probably wanted to use in the first place, if you are familiar with any number of JavaScript's useful array methods.

Here's one (out of many) more declarative ways of creating an array of invitations for a set of people.

const invitations = people.map((person) => `Hi ${person}, come to my party!`);
Enter fullscreen mode Exit fullscreen mode

It all sits on one line, yet is at the same time far more comprehensible. It's vastly more succinct, easy to write (and remember), all while being eminently clear at the same time.

That's what pursuing a declarative code style can deliver.

Unlike the first example, we didn’t need to create any confusing variables (such as i) or tell JavaScript how to go through the array. We just mapped (or iterated) over the array, added each person’s name to our invitation and it was returned to us

Summary

So which way do we want to write our code?

Let’s review our examples: what is more understandable, especially if we were looking at this code for the first time? What is more memorable?

Overtime, we’ve all had to review how to write a for-loop, precisely because it is imperative. For our sake and for others, the declarative style is what we want to pursue. It may seem like a confusing concept, but the reason we are making the distinction is for an important reason:

The way we write code should be tailored to the people reading and working with it, not the computers.

Scrutinize and reread your code for legibility and understanding, just as if you were writing an essay you wanted to be understood by everyone, even non-programmers, and strive for practices that make your code more declarative.

It won't just help people around you, but yourself as well, especially when you're revisiting code years later and you've long forgotten what it does.

Enjoy this post? Join The React Bootcamp

The React Bootcamp takes everything you should know about learning React and bundles it into one comprehensive package, including videos, cheatsheets, plus special bonuses.

Gain the insider information hundreds of developers have already used to master React, find their dream jobs, and take control of their future:

The React Bootcamp
Click here to be notified when it opens

Discussion (5)

pic
Editor guide
Collapse
nicolus profile image
Nicolas Bailly • Edited

It was an interesting read, but I have to gripes with the code examples you chose :

  1. invitations should not be declared as const if you're going to modify it.
  2. The imperative example feels needlessly convoluted, the most intuitive way to iterate with a for loop would look like this :
for (let person in people) {
    invitations.push(`Hi ${person}, come to my party!`);
}

Which I personally (coming from a PHP background, which didn't have arrow functions untill recently) find easier to understand than the "map" solution.

Collapse
jwp profile image
John Peters

The most intuitive way is purely subjective, map is an iterator too. I use it for everything.

Collapse
nicolus profile image
Nicolas Bailly

Yeah, I said "the most intuitive way with a for loop" ;-)
I'm comparing my version to the first example in the article.

I find for (let person in people) more intuitive than for (let i = 0; i < people.length; i++). It is indeed subjective, but I think most people would agree ?

Collapse
jwp profile image
John Peters

Instead of using this terminoly, I often say don't duplicate code ever.

Long before map, I created my own iterative call back routines because that pattern was just ugly.

If our code is ugly continuously refactor until it's beautiful. It's the same message

Collapse
zoedreams profile image
☮️✝️☪️🕉☸️✡️☯️

thank you.

what do you think of using a spread operator with your excellent example. How would persons map look?

global.talk.express.post(Api.URI[clazz.name], (..._) => clazz.resource(..._));