JS First Class Function
In this section, we will discuss the first class function, what it is, what the use is, and will also look at some of its practical implementations to understand its usage and work in a more précised manner.
What is JS First Class Function
We will see the implementation of these operations and will try to understand the usage of the first class method in a better way.
Storing in a Variable
The below example code is the implementation of storing a first class function in a variable:
In the above code:
let result = add(10, 20);
Here, we have assigned the add () function to a variable and passed two arguments in it. It is one way.
let result = sum(10,20);
Here, as we have already assigned the add () function to the sum variable so we can further assign the sum variable to the result and use it instead of using the add () function. It is because both sum and add points to the same address.
The complete code is as follows:Test it Now
After executing the code, we got the following output:
Passing the first class function as an argument to another function
As we have discussed that these first class functions can be stored in a variable which means that these functions behave like values also. Thus we can pass them as an argument to other functions too.
Let' s see the below example to understand the working and how we can pass it as other function's argument:Test it Now
We got the following output after executing the code:
In the above code,
Returning functions from functions
The first-class functions are the values only so we can also return it from a function. Let's see the below example code:Test it Now
In the above code,
Method 1: Using a Variable
In the above code we have used this method for invoking the anonymous function and in addition to it, we have the below example code that will help us to understand it:Test it Now
In this, we have simply created a constant variable callFunc, and to it, we have assigned the anonymous function. Then we have invoked the constant function with parenthesis.
Note: In calling such a function, we need to use another variable to which it should be assigned. Otherwise, it will not return the function which it is returning. If we return it without storing it in another variable, it would get returned directly.
Method 2: Using Double Parenthesis
The below code example will let you understand it:Test it Now
In the above code, for invoking the function, we have used double parenthesis, which is similar to storing the function to another variable and then invoking the variable with single parenthesis as we have done in Method 1.
So, it is all about First class functions, and we have better described its usage and its implementations.