First-class functions

A programming language is said to have First-class functions when functions in that language are treated like any other variable.

We can see some examples in Javascript:

Function as variable:

var foo = function() {
console.log("foobar");
}
// Invoke it using the variable
foo();

The difference from a function fooTwo(){console.log("foobar");}, is that foo is a function expression and so only defined when that line is reached, whereas  is a functionTwo() declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

Function as an argument:

function sayHello() {
return "Hello, ";
}
function greeting(helloMessage, name) {
console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");

Return a function:

function sayHello() {
return function() {
console.log("Hello!");
}
}

A function that returns a function called Higher-Order Function.

The term comes from mathematics, where the distinction between functions and other values is taken more seriously. Higher-order functions allow us to abstract over actions, not just values. They come in several forms.

Σχόλια