This lecture follows the first LearnProgramming route:
/course/functional
The central idea is familiar: spreadsheet formulas and code describe the same transformations.
Before naming a function, calculate directly.
| Spreadsheet | JavaScript |
|---|---|
=3 * 2 |
3 * 2 |
=10 + 5 |
10 + 5 |
=20 / 4 |
20 / 4 |
The operators are already programming: +, -, *, and /.
3 * 2 // 6
10 + 5 // 15
20 / 4 // 5
(3 + 2) * 4 // 20
The browser console and a spreadsheet are both places to test a calculation.
A spreadsheet column is a list of values. In JavaScript, the same idea is an array.
const A = [1, 2, 3, 4]
const B = [4, 5, 6, 7]
| Spreadsheet idea | JavaScript idea |
|---|---|
| Cell | Value |
| Column | Array |
| Formula | Function |
const scores = [85, 92, 78, 95, 88]
const name = "Alice"
scores[0] // 85
scores.length // 5
Give data useful names. Named data is easier to read and reuse than isolated numbers.
A function takes input, applies one rule, and returns output.
const add3 = x => x + 3
add3(1) // 4
add3(10) // 13
The same input produces the same output. This is a pure function.
Spreadsheet: =A1 + 3
JavaScript: const add3 = x => x + 3
Both mean: take a value and add three. The spreadsheet hides the function name; JavaScript lets us name and reuse it.
A lambda is a small function written where it is needed.
const double = x => x * 2
const greeting = name => "Hello " + name
double(5) // 10
greeting("Ada") // "Hello Ada"
x => x * 2 means “input x, output x * 2.”
const addTax = price => price * 1.1
addTax(100) // 110
// The same kind of function can be used inline later:
[100, 200].map(price => price * 1.1)
// [110, 220]
Small, single-purpose functions are the building blocks for larger programs.
Build a larger transformation from small ones.
const add1 = x => x + 1
const double = x => x * 2
const add1ThenDouble = x => double(add1(x))
add1ThenDouble(3) // 8
The output of one function becomes the input of the next.
Values → named data → pure functions → lambdas → composition
Functions can also choose an output.
const result = score => {
if (score >= 60) return "Pass"
return "Try again"
}
result(85) // "Pass"
result(42) // "Try again"
This matches the spreadsheet formula =IF(A1 >= 60, "Pass", "Try again").