Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a function to return a function?

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?

like image 202
davidx1 Avatar asked May 19 '16 23:05

davidx1


2 Answers

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.

like image 109
Paarth Avatar answered Oct 04 '22 05:10

Paarth


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:

  1. 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

  2. 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#

  3. 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;
      }
    }
    
  4. 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.

like image 24
Aditya Singh Avatar answered Oct 04 '22 06:10

Aditya Singh