First Class Functions - First Class Function
Functional Programming is a programming paradigm that allows you to use resources from mathematics and work with scalable systems that avoid side effects; many programming languages are fully functional or multi-paradigm. This series shows how to use the concepts of Functional Programming in JavaScript
Before proceeding, you might consider reading the first article in the series that discusses the concept of FP and prepares us for this series. In today's article, we will technically explain First Class Functions:
- https://bit.ly/3ecrRZk - Functional Programming - Everything You Need to Know! Article 1 of 10
What are First Class Functions
One of the features of functional programming present in JavaScript is First Class Functions; this is possible because in JavaScript functions are also treated as First Class Objects, which means that we can treat functions as values, and store them in variables and constants, pass functions as parameters in other functions, and even have functions as the return of other functions. This opens a range of possibilities in various Design Patterns, such as Higher Order Functions (High Order Functions), callbacks, among other resources, and becomes indispensable when we work with libraries that use the paradigm of Functional Programming such as Lodash, RamdaJS, or even React.
Storing as values in variables and constants
One of the features of a first-class function, also known as a first-class citizen, is the ability to store the function as the value of a constant or variable; in JavaScript functions are already objects like other data types.
In the example below, we create the function cl, an abbreviation for console.log, and later assign the constant escreve with the function cl. From that moment on, we can call the constant escreve as a first-class function.
function cl(x) {
console.log('console:' + x);
}
const escreve = cl;
escreve('Function as a constant value');
The function cl is assigned to the constant escreve.
Higher Order Function - High Order Function
Passing a function as a parameter to another function
Passing a function as a parameter allows you to create higher order functions; in the example below, the function retorna receives a function as a parameter. This function can execute any operation; within the function retorna, it could be called at any moment, in addition to being returned as was in the example.
Functions passed as parameters allow reuse smaller codes with simple logic to compose more elaborate logic, while still maintaining scope and avoiding side effects.
function cl(x) {
console.log('console:' + x);
}
const escreve = cl;
escreve('Function as a constant value');
function retorna(fn){
return fn
}
let exibe = retorna(escreve)
exibe('Passing a function escreve as a parameter and returning a function')
It's possible to call a function that has been assigned to a variable and execute it in another context.
Storing functions in a data structure
Besides storing functions as values of a constant or variable, it is also possible to assign this function as an index of an array and point to this array index by executing this function, even passing parameters.
In the example below, we create the array acoes storing two functions; once again the power of higher order functions comes into play, as it is possible to call the function cl and pass the parameter to execute, or even store the function with the parameter call, and then simply reference it as in the case of the second position with the function exibe.
. //previous code
.
.
let acoes = [cl, exibe('\nDisplaying: calling inside an array')]
acoes[0]('Displaying the function cl inside the array')
acoes[1]
Here is the complete code with the above snippet at the end of the code.
function cl(x) {
console.log('console:' + x);
}
const escreve = cl;
escreve('Function as a constant value');
function retorna(fn){
return fn
}
let exibe = retorna(escreve)
exibe('Passing a function escreve as a parameter and returning a function')
let acoes = [cl, exibe('\nDisplaying: calling inside an array')]
acoes[0]('Displaying the function cl inside the array')
acoes[1]
We have already used functions as parameter passing numerous times, as is the case with well-known callbacks, and also when we pass Arrow Functions as parameters, we are working with higher order functions.
In the following example, we see the command setTimeout() that receives a function as a parameter and a time in milliseconds that must be respected before executing the code. In this case, we are passing the time in seconds as a parameter, which will be converted into milliseconds.
const timeout = (seg) => setTimeout(() => cl(`Waiting ${seg}s`), parseInt(seg) * 1000);
timeout(5)
High Order Function in practice.
You may have already noticed that you use some resources of functional programming without knowing that it belonged to this programming paradigm, but the great thing about Functional Programming is besides conscious use, the use in conjunction with other resources of Functional Programming, such as declarative programming, immutability, and much more.
In the next article, we will continue learning new resources of functional programming. If you liked it, share this article with your friends, and remember that we have a Complete JavaScript Course sensational where we address many resources of the language in real projects, and if you already know JavaScript, we invite you to check out our Complete NodeJS Course that is unmissable.
See you in the next article! Until then!
Glaucio Daniel