• 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.

// imperative
const makes = [];
for (let i = 0; i < cars.length; i += 1) {
  makes.push(cars[i].make);
}

// declarative
const makes = cars.map(car => car.make);

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.

// imperative
const authenticate = (form) => {
  const user = toUser(form);
  return logIn(user);
};

// declarative
const authenticate = compose(logIn, toUser);

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.

Scroll Up