DEV Community

buddha lama
buddha lama

Posted on • Edited on

JS Function Factories

A function factory is a design pattern that includes creating and returning a function from another function.

Closure is used to achieve this pattern. Function factory can encapsulate configurations within functions. It is used to create multiple functions with similar behaviors.

Example:

function createOperation(operation){

  return function(a,b){
    switch (operation){
        case 'add': return a+b;
      case 'minus': return  a-b;
      default:
      return NaN;
    }
  }

}
const addition = createOperation('add');
console.log("addition:",addition(1,2))


const expo = createOperation('exponent');
console.log("Exponent:",expo(1,2))
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Top comments (0)