About

A programming language is said to support first-class functions if it treats functions as first-class objects.

The language supports:

  • constructing new functions during the execution of a program,
  • storing them in variable,
  • passing them as arguments to other functions,
  • and returning them as the values of other functions.

Resumed: you can return an inner function to be called sometime later on.

first-class functions are also known as:

A closure is a block of code that can be passed as an argument to a function. You can define a block of code and pass it around as if it were a string or an integer.

A closure is a variable storing:

A closure can continue to access a function’s scope (its variables) even once the function has finished running.

A closure is a callback function that can see non-local variables in the location where they were defined.

Closures are finding their way into many major languages, such as Java, C#, and PHP.

Implementation

The function values contain then:

  • the code required to execute when they’re called.
  • and any variables pointer they may refer

Functions that keep track of variables from their containing scopes are known as closures.

Example

A first class function (closure) that creates a context and retains its state.

function makeCounter() {
  
  var i = 0;

  return function() {
    console.log( ++i );
  };
  
}

var counter = makeCounter();
counter();
counter();
counter();
counter();

Documentation / Reference