Code of the Day
IntermediateThe runtime

Lab: closures and classes

Build a closure-based factory and a small class, with your work checked as you go.

Lab · optionalJavaScript / TSIntermediate16 min
Recommended first
By the end of this lesson you will be able to:
  • Use a closure to capture configuration
  • Implement a class with methods and state
  • Manage private state two ways

Optional lab. Practice the two ways JavaScript bundles behaviour with state — closures and classes. (These checkpoints are synchronous, so they grade instantly in your browser.)

Warm up: a closure that remembers

Run this — the returned function keeps access to count after makeCounter returns:

JavaScript — editable, runs in your browser

Checkpoint 1 — makeAdder

Write makeAdder(n) that returns a function which adds n to its argument. The returned function closes over n.

A closure-based adder factoryJavaScript

Write makeAdder(n) that returns a function. Calling that function with x returns x + n. Each adder is independent.

makeAdder(3)(4)7

The shape is return function (x) { return x + n; }; — the inner function remembers the n from the call that made it.

Checkpoint 2 — a Stack class

Implement a classic last-in-first-out Stack with push, pop, peek, and size, backed by an array.

Implement a StackJavaScript

Implement class Stack with push(x), pop() (removes and returns the top), peek() (returns the top without removing), and size(). Back it with an array.

s.push(1); s.push(2); s.pop()2

An array does all the work: this.items.push(x), this.items.pop(), this.items[this.items.length - 1] for peek, and this.items.length for size. The class just gives those operations clear names and hides the array behind them — encapsulation, the same goal the closure achieved differently.

Done?

Both green? You've now managed private state with a closure and with a class — two tools for the same job, each better in different situations.

Finished reading? Mark it complete to track your progress.

On this page