• Social

Imperative vs declartive programming

In the same way someone may write a formal or informal email, imperative and declarative programming are terms used to describe a style of writing code. Rather than getting bogged down in explaining the semantics of the terms, the simplest method to understand them is to look at the below examples.

[pastacode lang=”javascript” manual=”%2F%2F%20imperative%0Aconst%20makes%20%3D%20%5B%5D%3B%0Afor%20(let%20i%20%3D%200%3B%20i%20%3C%20cars.length%3B%20i%20%2B%3D%201)%20%7B%0A%20%20makes.push(cars%5Bi%5D.make)%3B%0A%7D%0A%0A%2F%2F%20declarative%0Aconst%20makes%20%3D%20cars.map(car%20%3D%3E%20car.make)%3B” message=”” highlight=”” provider=”manual”/]

Both examples do the same thing, which is to create a new array of car makes from an array of car information. The difference is that the declarative method is  much easier to read. It’s also easier to reason about as it describes the solution instead of displaying the procedure. Taking it a step further you can write declarative code by using a compose() to streamline your functions.

[pastacode lang=”javascript” manual=”%2F%2F%20imperative%0Aconst%20authenticate%20%3D%20(form)%20%3D%3E%20%7B%0A%20%20const%20user%20%3D%20toUser(form)%3B%0A%20%20return%20logIn(user)%3B%0A%7D%3B%0A%0A%2F%2F%20declarative%0Aconst%20authenticate%20%3D%20compose(logIn%2C%20toUser)%3B” message=”” highlight=”” provider=”manual”/]

The benefits of this are simply that it saves on time for the developers, which is why there has been a big push in recent years to this style of programming. React for example, is known as declarative, whereby you are thinking about WHAT you want to happen, rather than HOW you want it to happen.

ES6 has lots of new declarative methods such as reduce(), map() and filter() which are abstractions of for loops. Another fantastic form of declarative programming are Promises or async / await. These are abstractions of complex functions that in previous versions of JavaScript would have taken a lot more code and brain power to achieve the same thing.

The point of the above is to identify declarative programming as a way to streamline your code and ultimately make you a better software engineer.