First-class Function

Definition – What is First-class Function?

In computer programming, when a function can be passed as an argument through other function is called the first-class function. First-class functions act like ordinary values of a variable. Because the first-class function can be assigned in a variable. And then you can call the variable in other function simply by calling the variable name. It will return the output of the first-class function as a value.

First-class function is a very useful feature in programming. It is the alternatives of nesting function. But It has extra features that are not possible in function nesting.

Not all the programming languages support the first-class function. Languages including PHP, Python, Perl, Lua, and Javascript support first-class function definition.

First-class Function – Explanation

In some programming languages, to support the first-class function, sometimes it needs the support of anonymous function or function literals. One important thing about the first-class function – it is an essential feature to support functional programming style.

In general, the First-class function involves some other Programming concepts and features including nested function, anonymous functions, higher order function: Passing functions as an argument, callback function, etc. And all the concepts mentioned above are properties of functional programming language.

First class functions can be implemented or called by following two different ways. First one is using a variable and the second method is calling the function directly by the function name with parentheses.

Example: First-class function in Javascript

The below example shows how to implement a first-class function in Javascript:

function exFunc() {
   return "Hello, ";
}
function greetFunc(Message, name) {
  document.write(Message() + name);
}
greetFunc(exFunc, "PrograCoding!");

Output:

Hello, PrograCoding!

Learn First class-function implementation
How to write first-class functions in Javascript
How to write first-class functions in Python
How to write first-class functions in PHP
How to write first-class functions in Perl

Tags