CodeBlanks Logo Icon CodeBlanks

Factory functions

JavaScript course · Intermediate · Lesson 14/134

Learn how a returned function captures private state.

Factory function

A factory function is a function that creates and returns a new function. The returned function captures the factory's local variable, which becomes a private state hidden from outside.

Each call to the factory creates a fresh scope, so a new closure is born. Two counters are therefore independent: each has its own count.

Independent state

If you call makeCounter() twice to make two counters, each call creates its own let count = 0. The two returned closures bind to different count variables.

Incrementing one does not affect the other. This is the power of closures: the same factory code produces many instances with independent state.

Exercise Write a counter factory

Define a function called makeCounter(). Inside it, initialize a private counter with let count = 0. The inner function it returns should increment count and return it. Then create two separate counters (c1 and c2) and call each once, logging the result.

Show example solution
function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const c1 = makeCounter();
const c2 = makeCounter();
console.log(c1());
console.log(c2());

Test yourself

  1. What happens when two counters are created with makeCounter()?

    • They share the same counter
    • Each has its own independent counter
    • Only the first one works
    • Both always return zero
    Show answer

    Each has its own independent counter — Correct. Each call creates a new count variable; the two closures bind to different variables.

  2. Call the first counter

    const c1 = makeCounter();
    const c2 = makeCounter();
    console.log(c1____());
    console.log(c2());
    Show answer
    const c1 = makeCounter();
    const c2 = makeCounter();
    console.log(c1()());
    console.log(c2());
  3. Match the factory concepts

    factory function
    A function that builds functions
    private state
    State hidden from outside
    counter
    Closure that increments

All lessons in Intermediate