Concepts Over Syntax

Recall from Thinking in Expressions that imperative programs are built from statements.

These statements are mechanical instructions for the computer that often have nothing to do with the problem we’re trying to solve.

Let’s read this example again:

let numbers = [1, 2, 3];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

What is the problem we’re trying to solve here?

Ultimately, we’re trying to calculate the sum of a bunch of numbers.

However, most of this program has nothing to do with the problem we’re trying to solve:

  • What is i, and what does it have to do with summing numbers?
  • Is the length of the array actually relevant when summing numbers?
sum += numbers[i]

This is the only line in the entire program that is relevant to the problem we’re trying to solve. Everything else is just noise.

Let’s rewrite this in a functional style using these building blocks:

  • [1, 2, 3]: our array of numbers

  • [1, 2, 3].reduce: a function that reduces [1, 2, 3] into a single value

  • (a, b) => a + b: a function that adds two numbers

  • 0: initial value for the reduction

[1, 2, 3].reduce((a, b) => a + b, 0)

Our functional program is simple, concise, and focused on solving the problem. It focuses on what we want out of the program, rather than how to solve it mechanically.