Function - First Class Function (Closure|Function Literal)

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

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

4 - 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();

5 - Documentation / Reference

code/function/closure.txt · Last modified: 2017/09/17 17:51 by gerardnico