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' };
});
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.
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.
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.
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.
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 _.bind
ing _.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'});
They are called higher order functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With