Blackb3ard
Blackb3ard

Reputation: 65

Is there a name for returning an anonymous function from a function?

function f1() {

  function f3() {
    v = 3;
    return function(i) {
      return i + v;
    }
  }
  console.log( f3()(5) );
}
f1();

I have been trying to find a source where I can read about returning an anonymous function as in this example. Also how the variable is passed f3()(5).

Are there terms for this? Links are appreciated.

Upvotes: 3

Views: 60

Answers (2)

Nickolay
Nickolay

Reputation: 32063

The inner function is called a closure:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

The term "currying" refers to a more general mathematical concept and is programming language-independent. I also think it's misused often because the word is so cute.

Upvotes: 2

Oriol
Oriol

Reputation: 288100

I think you mean currying:

The technique of transforming a function that takes multiple arguments into a function that takes a single argument (the first of the arguments to the original function) and returns a new function that takes the remainder of the arguments and returns the result.

Upvotes: 5

Related Questions