JavaScript Function Factories and Independent State
Quick answer
A function factory returns a callable value configured by the inputs and local state of that particular invocation.
How it works
Create a local binding inside the factory and return a function that reads or updates it. A factory can produce a family of related behaviors without exposing its local variables as object properties. Each call creates fresh local state; sharing external objects intentionally changes that isolation.
function multiplier(factor) { return n => n * factor; }const double = multiplier(2); const triple = multiplier(3);console.log(double(4), triple(4));Expected output in Node.js:
8 12Each factory invocation binds a different factor.
function counter(start) { let n = start; return () => ++n; }const a = counter(2); const b = counter(9);console.log(a(), a(), b());Expected output in Node.js:
3 4 10Each counter advances its own state.
Common mistakes
Do not declare per-instance state outside the factory unless you intend to share it.
Practice
Create two counters with different starts and compare interleaved calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Function Factories and Independent State — Knowledge Check
Apply the taught concept and predict the output.
Where should a counter factory declare independent state?
What does multiplier(2) return?
When can two factory results share mutable state?
What is the exact console output in JavaScript Function Factories and Independent State example 1?
function multiplier(factor) { return n => n * factor; }const double = multiplier(2); const triple = multiplier(3);console.log(double(4), triple(4));What is the exact console output in JavaScript Function Factories and Independent State example 2?
function counter(start) { let n = start; return () => ++n; }const a = counter(2); const b = counter(9);console.log(a(), a(), b());