4

Javascript allows us to write functions that use their parameters to build and return another (often anonymous) function with specific behaviour. Currying is an example of this.

To illustrate, this approach can be used to elegantly sort an array of objects on an arbitrary property:

var sortOn = function(property) {
  return function(a,b) {
    return a[property].localeCompare(b[property]);
  };
};
var myArray = [ {id:1, title:'Hello'}, {id:2, title:'Aloha'} ];
myArray.sort( sortOn('title') ); // Aloha, Hello
myArray.sort( sortOn('id') );    // Hello, Aloha

Generally speaking, is there a word for a Javascript function that, based on its parameters, returns another function?

aaaidan
  • 7,093
  • 8
  • 66
  • 102

2 Answers2

3

A function that returns a function is called a higher order function.

It's a functional concept which is mainly used to abstract away parts of doing something into smaller bits, making it much quicker to code efficiently and cleanly.

Your function is a higher order function as it returns a function that creates a closure from its arguments - it's as simple as that. A higher order function can also be one that returns something by a function which uses the result of another function given as an argument to make the result.

A functor is just a synonym for a function object - that is, you are able to pass a function as though it is any ordinary variable. In JavaScript, all functions (whether declared, anonymous/named function expressions, or functions made using the function constructor or even built-in functions) can be passed as ordinary variables, therefore functions in JavaScript are first-class objects. This does not really apply to your function though, as you are returning a function, not passing a function as an argument.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
2

In computer science generally, a function that operates on functions as input or output is called a "higher order function."

user2759991
  • 138
  • 6