Functions & Scope

Difficulty
Importance

The problem

Programs need to package a sequence of steps into a reusable, nameable unit that can be invoked with different inputs — without this, every computation would have to be written out in full every time it's needed, with no way to isolate a piece of logic from the rest of the program's state.

Why now

Functions and relations already gave the abstract guarantee — same input, same output — but a mathematical function has no notion of an environment, local names, or being defined once and called many times. Programming functions implement that guarantee while adding the practical machinery (parameters, local scope, a call stack) math functions never needed.

Mental model

A function is a mini-program with its own labeled boxes (local variables) that disappear when it returns; scope is just 'which boxes can this line of code see.' Closures happen when an inner function keeps a reference to an outer function's boxes even after the outer function has returned — scope outliving its creator.

Requires

Unlocks

Related

Used in

Projects

  • Write a counter factory function that returns a closure over a private counter variable, with no way to access the counter except through the returned function
  • Predict, then verify, the output of a nested-scope quiz (shadowed variable names at three levels)

Examples

  • function add(a, b) { return a + b; } — a, b, and the return value live only inside one call
  • A closure: function makeCounter() { let n = 0; return () => ++n; } — the returned function keeps access to n forever

Resources

Mastery checklist