Write declarative code

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Write declarative code

There are two kinds of code:

  1. Imperative code
  2. Declarative code

Imperative code

Imperative code tells a program what do do.

For example, if you write 1 + 1, you’re telling the program to add 1 to 1, which gives 2. This line of code is imperative because you tell the program what to do.

Another example of an imperative code is a for loop. Let’s say you have a fruitBasket with an array of fruits. You want to count the number of apples in the group.

Here’s what you might do if you used a for loop.

const fruitBasket = ['apple', 'banana', 'pear', 'apple']
let appleCount

for (let fruit of fruitBasket) {
  if (fruit === 'apple') {
    appleCount = appleCount + 1
  }
}

console.log(appleCount) // 2

You can see how our thought processes get translated directly into code—first, loop through the fruitBastket; then, check if the fruit is an apple; if the fruit is an apple, add one to appleCount.

Declarative code

Declarative code lets a program do things without worrying about implementation details. The details is often left to a function.

Here’s the above code rewritten in a declarative form:

const fruitsBasket = ['apple', 'banana', 'pear', 'apple']
const appleCount = countApples(fruitsBasket)

Notice we don’t care about what happens in countApples. All we care about is countApples return the number of apples in the array passed to it.

countApples can be written with imperative code, and we would have been fine with it:

// Imperative countApples
const countApples = array => {
  let appleCount

  for (let fruit of array) {
    if (fruit === 'apple') {
      appleCount = appleCount + 1
    }
  }

  return appleCount
}

If you’re savvier with array methods, you could write countApples with the filter method and the length property. This combination is declarative because you can tell what happens at a glance, through the methods and properties used.

// Declarative countApples
const countApples = array =>
  array
    .filter(item => item === 'apple')
    .length

Don’t get hung up over imperative or declarative code

Declarative code is always better than imperative code, but they’re harder to write in the beginning.

Don’t try to write declarative code from the get-go. What’s important is to get the program working first—even if you write imperative code. Once the program works, you can refactor (meaning, go back and edit your code) and change imperative code into declarative code.

Overtime, you’ll begin to write declarative code automatically.