Imperative vs. Declarative Programming, what is the difference?9 min read

If you already have experience with programming for a while, perhaps you have encountered some terms like imperative, declarative programming for a couple of times. However, up to this point, sadly you still don’t really understand what they really are. In this article, we are going to illumine those concepts. At the end of the day, you will twig why this definition:

Imperative programming is like how you do something, and declarative programming is more like what you do, or something.”

Both imperative and declarative programming are classified as the common programming paradigms (programming paradigms are a way to classify programming languages based on their features).

Imperative programming

Imperative programming is like when you ask your friend to write an essay for you, you give him detailed instructions and how should he write it even he doesn’t demand it to get the desired result.

Looking back at the definition above, we see imperative programming is like how we do something, to envision what it is, let’s make a real-world example first.

Example: I’m in the park which nearby your house but I still cannot find a way to get your house. How do I get your house from here?

Response: Find the entrance of the park, and stand from the connecting point toward the road, then go straight to the right-hand 400m you will see an intersection, then you continue to turn right, go straight for another 200m and go to 7830 Pineknoll Road, which is my home address.

So, we reach the desired location, which is a home address by giving detail instructions on how to get it.

Likewise, Imperative programming is a programming paradigm that uses a sequence of statements to determine how to achieve a certain goal. Imperative programming includes procedural programming and object-oriented paradigms, but in the scope of this article, we don’t talk about those concepts much.

The conspicuous examples of imperative programming are for, while loops, if, else, classes, objects.

Now, let’s do some imperative programming style examples in JavaScript:

  1. Presume we have an array with some elements and want to return a new array with double value for each array’s item:
function double(arr) {
    let rs = [];
    for (let i = 0; i < arr.length; i++) {
        rs.push(arr[i] * 2);
    }
    return rs;
}
double([2, 3, 4]); // [4, 6, 8]

In this example above, we reached a certain goal by giving a sequence of statements in which we used for loop to loop from the first element of the array to the end and each of the iteration we double the value of each item and put it into the rs variable, finally we return the result, rs.

2. Now, let’s write a function named factorial, which takes a number as an input and resulting in the factorial result of this number, how do we get it by using for loop:

function factorial(n) {
    let total = 1;
    if (n == 0) {
        return 1;
    }
    for (i = 0; i < n; i++) {
        total = total * (n - i);
    }
    return total;
}
factorial(5); // 120

In the example above, as we can observe, to reach the goal we again need to use a for loop, and also if statement. First, we initialized a variable that holds the result named total and we checked the input, if input equals 0, then immediately return 1, but if not, the next sequence of code was being proceeded. Inside the for loop, we iterated from 0 to n - 1, then the result was being added to total after each iteration. After all, we return the result. The reason inside a loop we didn’t set the condition as i <= n, instead, we just did i < n because, if i <= n, then:

total = 1 * (5 - 0);
total = 5 * (5 - 1);
total = 20 * (5 - 2);
total = 60 * (5 - 3);
total = 120 * (5 - 4);
total = 120 * (5 - 5); 
total = 0

3. Write another function, which called addSum which takes in an array and returns the result of adding up every item in the array:

function addSum(arr){
    let rs = 0;
    for(let i = 0; i < arr.length; i++){
        rs += arr[i];
    }
    return rs;
}
addSum([1, 2, 3, 4, 5]); // 15

As two of the examples above, in this example, with imperative style, we continued to use a for loop to loop through the array elements and adding them up to the rs variable, then we return the result.

4. We again, write a function named filterArr which takes an array as an argument and return its elements which are greater than 5:

function fitlerArr(arr){
    let rs = [];
    for(let i = 0; i < arr.length; i++){
        if(arr[i] > 5){
            rs.push(arr[i]);
        }
    }
    return rs;
}
fitlerArr([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [6, 7, 8, 9]

We get the desired result by giving the instructions, in which we create a for loop and filter the values which are greater than 5 then push those values to the rs variable.

Declarative programming

Declarative programming is a contrast programming paradigm compared with imperative programming. This paradigm emphasizes the concept of what to do rather than how to do it. Declarative programming is like when you ask your friend to write an essay, you don’t care how does he write it, you just want to get the result.

Now we look back to the real-world example as we mentioned earlier in the Imperative programming section:

Example: I’m in the park which nearby your house but I still cannot find a way to get your house. How do I get your house from here?

Response: 7830 Pineknoll Road, Sykesville, MD 21784

So, by this declarative response, I don’t care how does he get to my house’s location, I just give him the address then wait for him coming for me (the result).

Functional programming is a form of declarative programming, in which the desired result is declared as the value of a series of function applications. People often use those terms interchangeably. The outstanding examples of a functional programming language is Haskell. If you want to learn more about functional programming or declarative programming, you should consider reading this article that gives you a reason to learn Haskell and also learning resources. Underneath, I also introduce some concepts and code examples in the Haskell programming language.

In JavaScript, besides supporting imperative programming, you can also write declarative (functional) programming at the same time by using some of those function map, reduce, filter. I’m going to write another article about those things soon!

Now we listed 4 examples in imperative programming section again and see what we will do to make those declarative:

1. Double value of each item in an array:

In JavaScript:

function double(arr) {
    return arr.map(element => element * 2);
}
double([1, 2, 3]) // [2, 4, 6]

In Haskell:

map (*2) [1, 2, 3] -- [2, 4, 6]

2. Write a factorial function with declarative style (Haskell):

factorial n = product [1..n]
factorial 5 -- 120

3. Write a function which takes in an array and returns the result of adding up every item in the array:

In JavaScript:

function reduceArr(arr){
    return arr.reduce((prev, next) => prev + next, 0);
}
reduceArr([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // 55

In Haskell:

sum [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -- 55

4. Filtering values of an array that greater than 5 and return the output:

In JavaScript:

function filterArr(arr){
    return arr.filter(value => value > 5);
}
filterArr([1, 2, 3, 4, 5, 6, 7, 8, 9]); // [6, 7, 8, 9]

In Haskell:

filter (>5) [1, 2, 3, 4, 5, 6, 7, 8, 9] -- [6, 7, 8, 9]

NOTE: In Haskell, some values and then enclosed by the square braces [] we call it a list not array and list in Haskell is not the same as array in JavaScript, for example if you want to get the length of an array in JavaScript which just takes the constant time to get the result, but finding the length of a list in Haskell, you have to traverse to all the element of the list and get the result, which means it takes the linear time in Haskell to get the length of the list. Nonetheless, for simplify, I just call it an array for JavaScript as well as Haskell.

In all four of the examples above, we always get the desired output even we don’t care how does it get the values and don’t really know how it could be implemented. In the first example, we used map to double every each item in the array. Second, we used product function in Haskell to get the factorial number. Third, we used reduce and sum in JavaScript and Haskell respectively to get the sum value of all the array’s elements. Fourth, finally, we used filter function to get some values in the array that passed the certain condition.

Some languages, such as SQL or HTML are also declarative languages, consider those examples:

SELECT * FROM Users WHERE Country = ’Canada’;
<h1>HTML is awesome!</h1>
<p>Hypertext Markup Language is the standard markup language for creating web pages and web applications. With Cascading Style Sheets and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web.</p>

As those examples above, we are achieving something without instructions on how to do it. The implementation of selecting all the users from Canada may be transparent to you and me. Displaying h1 heading and a paragraph without caring how the browser could parse your sentences and displaying it to the screen.

Now let’s sum up what we’ve learned into a comparison table:

ImperativeDeclarative
Definitiona sequence of statements to determine how to reach a certain goal.merely declares what
to do to get the desired result, but not how to compute it.
ClarityClearTransparent, Abstract
FlexibilityMore flexibleLess flexible
ComplexityIncreases the complexity of a programSimplifes the program
LanguagesC++, Java, Smalltalk, C#, etc…HTML, Haskell, SQL, Agda, PureScript, Elm, etc…
Example
I’m in the park which nearby your house but I still cannot find a way to get your house. How do I get your house from here?Find the entrance of the park, and stand from the connecting point toward the road, then go straight to the right-hand 400m you will see an intersection, then you continue to turn right, go straight for another 200m and go to 7830 Pineknoll Road, which is my home address.7830 Pineknoll Road, Sykesville, MD 21784
Ask a friend to write to you an essayGive him detailed instructions on how should he write it to get the result.Get the result.
Double value of each item in an arrayfunction double(arr) {
let rs = [];
for (let i = 0; i < arr.length; i++) {
rs.push(arr[i] * 2);
}
return rs;
}
double([2, 3, 4]); // [4, 6, 8]
map (*2) [1, 2, 3] -- [2, 4, 6]
Factorialfunction factorial(n) {
let total = 1;
if (n == 0) {
return 1;
}
for (i = 0; i < n; i++) {
total = total * (n - i);
}
return total;
}
factorial(5); // 120
factorial n = product [1..n]
factorial 5 -- 120
Sum of the array’s elementsfunction addSum(arr){
let rs = 0;
for(let i = 0; i < arr.length; i++){
rs += arr[i];
}
return rs;
}
addSum([1, 2, 3, 4, 5]); // 15
sum [1, 2, 3, 4, 5] -- 15
Array’s items are greater than 5function fitlerArr(arr){
let rs = [];
for(let i = 0; i < arr.length; i++){ if(arr[i] > 5){
rs.push(arr[i]);
}
}
return rs;
}
fitlerArr([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [6, 7, 8, 9]
filter (>5) [1, 2, 3, 4, 5, 6, 7, 8, 9] -- [6, 7, 8, 9]

Facebook Comments

Previous Article
Next Article

Leave a Reply

avatar
  Subscribe  
Notify of

Sign up for newsletter

* indicates required

Categories

Archives