specialblend.dev

THINKING IN EXPRESSIONS

October 29, 2024

STATEMENTS VS. EXPRESSIONS

Imperative programs are built from statements, and read top to bottom.

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

Functional programs are composed of expressions, and read inside out.

Here’s the same program written in a functional style:

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

Think of expressions like boxes.

These expressions are atomic (can’t get any smaller):

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

We can make bigger expressions containing smaller ones:

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

Zoom out a little more:

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

Zoom out all the way:

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

💡 Tip: any time you read code, look for the smallest atomic expressions, and see how they’re composed into larger expressions. With practice, your brain will automatically start painting little boxes around them.

Expressions Are Simpler to Reason About

FP offers a simpler way of looking at the world:

Expressions Are Simpler to Refactor

  1. Find the expression you want
  2. Draw a box around it
  3. Move it around anywhere inside its parent “box”

For example, let’s extract [1, 2, 3] into a variable:

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

(becomes)

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

Extract function (a, b) => a + b into a variable:

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

(becomes)

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

Wrap it into a resuable function:

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


SUMMARY

home