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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Be careful when using the term "functor": it has multiple, unrelated meanings in functional programming.
@MattFenwick: while true, I attempted to use it as given in the context given.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.