profile
Juan Vega
Software Developer | Writer | Nerd

Imperative vs. Declarative Programming

One of the first programming paradigms that developers learn is imperative programming. The process of writing code that follows a specific set of steps to accomplish a final goal.

In contrast, declarative programming takes the approach of focusing on the outcome and abstracting the steps themselves.

The interesting thing to note is that most developers choose imperative programming first not because of a conscious choice, but because it makes the most sense. At least initially.

As an example, assume that you have been assigned a task that involves taking an array of integers and returning a new array with those integers multiplied by 10.


              let arr = [0,1,2,3,4]
            

In the imperative approach to solving this task, you create a new array and use a for loop to iterate over the original array and multiply the integers at the same time.


              let newArray = [];

              for(let i = 0; i < arr.length; i++){
                newArr[i] = arr[i] * 10;
              }
            

If you then printed out the contents of newArray onto the screen, you should see


              [0,10,20,30,40]
            

This method of programming is so common because it’s how most beginner courses teach programming. To help you remember, here is a common explanation using non-technical terms.

Say you are having a dinner party at your home and you invited your new co-worker to join. They have of course never been to your house, so you would give them explicit directions.

Go left on Random Street, turn right on New Road and then keep straight on the fork.

This is an imperative approach because you are describing in detail how to get to your house. If you are off by even a single direction, your guest will be lost and the goal will not be achieved.

In the approach, you would have just sent them the address to your home. You would not be concerned how they got to your house, only that they did.

Using code, declarative programming would look like this.


              let arr = [1,2,3,4,5];

              let newList = arr.map(function(item){
                return item * 10;
              });
            

The map function abstracts how it iterates over the contents of the arr array and instead allows you to focus on the outcome. In this case, multiplied the original list by 10;

In most cases, declarative programming is better than imperative programming. It’s much easier to understand at first glance and it allows you to write less code to accomplish the same task.

Ultimately though, it really depends on what you are trying to accomplish. There are pros and cons to each approach but at least know you have a better understanding on both imperative and declarative rendering.