Lesson 1.7Code~55 min
Closures & recursion
Functions that remember, and functions that call themselves — the two ideas inside every autograd engine.
Module 1 · 0/8 done
Functions that remember
You know functions can be passed around like values. They can also be created by other functions. When that happens, the inner function keeps access to the variables around it — even after the outer function has finished. That “backpack” of remembered variables is called a closure.
// A function can build and return another function.
function makeMultiplier(k: number) {
return (x: number) => x * k // this inner function "remembers" k
}
const double = makeMultiplier(2)
const triple = makeMultiplier(3)
console.log(double(10), triple(10))
// That memory is called a closure. It can even hold state that changes:
function makeCounter() {
let count = 0
return () => {
count++
return count
}
}
const next = makeCounter()
console.log(next(), next(), next()) // 1 2 3 — count lives on between calls
const other = makeCounter()
console.log(other()) // 1 — a separate counter with its own count
Press Run (⌘/Ctrl + Enter) to see output here.