THINKING IN EXPRESSIONS
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:
- Every value is an expression
-
Strings, numbers, and booleans are expressions
-
Arrays and objects are expressions
-
Functions are expressions
-
-
Any expression can be replaced with its simplest value without changing the program:
-
1 + 2
can be replaced by3
and vice versa -
5 * 3
can be replaced by15
and vice versa -
Math.sqrt(16)
can be replaced by4
and vice versa -
[1, 2, 3].reduce((a, b) => a + b, 0)
can be replaced by6
and vice versa
-
Expressions Are Simpler to Refactor
- Find the expression you want
- Draw a box around it
- 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
- Every value is an expression
- Expressions can be replaced by their simplest values
- Expressions are simpler to refactor and reason about