Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do you call a function that takes a value and returns a function that returns that value?

Tags:

javascript

I am trying out a more functional style with Javascript using Lodash and compose. I notice that I sometimes need a function that returns a value. So was wondering what this was called so I can find out if Lodash actually has this method.

var returnFn = function (i) {
  return function () {
    return i;
  };
};

Example:

_.compose(doSomething, returnFn({ foo: 'bar' });

Instead of:

_.compose(doSomething, function () {
    return { foo: 'bar' };
});
like image 707
Pickels Avatar asked Sep 06 '13 14:09

Pickels


People also ask

What is it called when a function returns a value?

Return statements in many programming languages allow a function to specify a return value to be passed back to the code that called the function.

What is the return type of the function is called?

The result of a function is called its return value and the data type of the return value is called the return type. Every function declaration and definition must specify a return type, whether or not it actually returns a value.

How do you call a function that returns another function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Which method return type returns a value?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.


2 Answers

What do you call a function that takes a value and returns a function that returns that value?

What you have seems to be a curryied identity function, which in Haskell is known as const. As it returns a function, it is a higher order function, maybe also called function factory. The returned function - a constant function - is a closure as it has access to the outer function's argument.

so I can find out if Lodash actually has this method.

No, it doesn't. However, you can easily compose it yourself by _.binding _.partial to the _.identity function:

var returnFn = _.bind(_.partial, null, _.identity);

Your plain implementation will be lots of faster though…

_.compose(doSomething, returnFn({ foo: 'bar' }));

What you're doing there is just partial application, and you should not use compose for it. Go with

_.partial(doSomething, {foo: 'bar'});
like image 88
Bergi Avatar answered Oct 01 '22 19:10

Bergi


They are called higher order functions.

like image 41
Ingo Kegel Avatar answered Oct 01 '22 20:10

Ingo Kegel