I'm wondering, why do I sometime see functions that returns a function?
For example this answer from this question: AngularJS custom filter function
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
What does it mean to have a function that returns another function that returns a value?
There are many cases where you'd want to return a function. In this situation specifically it deals with how angular defines filters. The outer function is meant to handle any dependencies that might need to be injected or any variables that might need to be specified. The inner function is the actual filter step that is applied on a collection to return a smaller collection.
All functional languages and hence JavaScript allows for **Higher order functions*, wherein functions are treated as first class members of the language and can be returned from another function or passed as parameter to another functions. This allows for a lot of power in the language enabling things like:
Closures: Closures are again different kind of beast and adds a lot of power to asynchronous programming via callbacks. You can read more about closures here: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
Abstraction: When you return a function exposing only certain part of functionality, you can always hide some part of it using local variables. This allows for abstraction in a language like javascript wherein you don't have public
, private
access specifiers as in other languages like Java or C#
Currying: You can implement currying in javascript by returning functions applied on selected attributes. E.g. Define a function sum such that the parameters can be partially applied to it. sum(3)(4)
function sum (a) {
return function (b) {
return a + b;
}
}
Factory pattern: You can use Higher order functions to generate functions and use the function as a factory
There are many other features in JavaScript language possible only because of the capability to return 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