Declarative Programming

Declarative programming is a style of programming that can make your code more concise and easier to read. It is also a subset of functional programming, a programming paradigm growing in popularity among JavaScript developers.

Declarative vs Imperative

When comparing declarative programming with imperative programming, it is often said to be the WHAT vs HOW. In traditional imperative programs, we tell the computer HOW to complete a task, whereas, in declarative programming, we tell the computer WHAT we want. Let's look at a real-world example.

Let's say we are hungry, and we want a sandwich. An imperative request might look like this:

GET OUT BREAD, PEANUT BUTTER, AND JELLY
TAKE TWO SLICES OF BREAD
PUT PEANUT BUTTER ON ONE SLICE
PUT JELLY ON THE OTHER SLICE
PUT SLICES TOGETHER

Whereas a declarative request could look like this:

MAKE ME A PEANUT BUTTER AND JELLY SANDWICH

In this second request, we are not worried about the particulars of how to make the actual sandwich. We tell the computer what we want and let it figure out the rest.

But, the good news is that we already have experience with declarative programming in the form of HTML. HTML is a declarative programming language. When we want to display our page title as a heading 1, we do not have to tell the computer each step. Instead, we tell the computer what we want by using the <h1> tag.

<h1>Page Title</h1>

Now let's look at how to write Declarative JavaScript.

Declarative JavaScript

Most of the JavaScript we have written up to this point has been imperative. Each script is providing each step the computer must take to complete a task. Let's look at a simple example.

In this example, we want to take an array of numbers and create a copy containing only even numbers.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const evens = []

for (const number of numbers) {
  if (number % 2 === 0) {
    evens.push(number)
  }
}

The example above is not particularly complicated, but we still had to provide each step to the computer. Now, let's look at how this code could look if we used declarative JavaScript. Don't worry too much about the syntax at this point. We will cover the specifics later.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const evens = numbers.filter(number => number % 2 === 0)

Using the filter method and an arrow function, two topics we will discuss later, we were able to complete the same task with far less code. Furthermore, the code is easier to read. No longer are we providing each step. We are simply requesting WHAT we want.

Now that we feel for declarative programming let us look at the tools we will need, starting with the arrow functions.