liveBook · Manning

Factory

As explained in Grokking Simplicity

A function factory is a function that creates and returns other functions, often with a shared behavior or configuration.

A function factory is a function that creates and returns another function. It automates repeated function creation while applying shared behavior, such as logging or error handling. section 11.4

A factory makes reuse practical by:

  • Wrapping different functions with the same logging and try/catch behavior. section 11.4
  • Returning inner functions that preserve supplied configuration, as makeAdder does with n. section 11.4
  • Returning the wrapped function’s result and adapting argument handling when needed. section 11.4

One logging factory, several functions

function wrapLogging(f) { return function(arg) { try { return f(arg); } catch (error) { logToSnapErrors(error); } }; } var saveUserDataWithLogging = wrapLogging(saveUserDataNoLogging); var fetchProductWithLogging = wrapLogging(fetchProductNoLogging); section 11.4

function makeAdder(n) { 
    return function(x) { 
        return n + x; 
    }; 
}

Compare a small factory that creates configured adders, making the returned function’s shared behavior easy to see. section 11.4

How Grokking Simplicity covers it

How deep it goes
Defines returned functions, wrappers, results, and argument handling, but defers broader variable-argument support to ES6 features.
Examples
Uses logging wrappers, saveUserData, fetchProduct, and makeAdder to demonstrate repeated creation and configured behavior.
What it assumes
Assumes familiarity with JavaScript functions and introduces assigning returned functions to variables.
What you can do after
Build reusable functions that apply consistent behavior to multiple underlying functions.
How it connects
Connects first-class functions with function wrappers, logging, error handling, and reusable configuration.

Also explained in

Compare how 11 books explain factory →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.