First Class functions in Javascript Explained

first class functions

Introduction to first class functions in Javascript.

A function is considered to be first class if it can be treated as a variable ie the function behaves just like any other variable.

With first class functions you can achieve the following:

  • The function can be assigned to a variable, array or in an object as a value.
  • The function can be a return value for another function
  • The function can be passed as an argument to another function.

Example 1: Returning a function from another function.

A function that will always return a function is referred to as a higher order function. In this example we will create a function called helloWorld that will return another function called greeting. Remember we are treating our function as a value since it is a first class function so we can return it without an error.

function helloWorld()
{
    return function greeting()
    {
        console.log("Hello world")
    }
}

Now, how do you call the above function? There are two ways to do this, lets look at the first method.

Method 1

To call our helloWorld function we will store its return value in a variable and call the variable as a function.

function helloWorld()
{
    return function greeting()
    {
        console.log("Hello world")
    }
}

const returnedFunc = helloWorld()
returnedFunc()

/*Output
Hello world
*/

method 2:

The second method is to use double parentheses to invoke the function as shown in the following example.

function helloWorld()
{
    return function greeting()
    {
        console.log("Hello world")
    }
}

helloWorld()()


/*Output
Hello world
*/

Example 2: First class function assignment to a variable.

In the following example we assign the function Hello to a variable directly when creating the function. The function can then be invoked or called from the variable as shown.

const myfunction = function Hello()
{

        console.log("Hello")
    
}

myfunction()


/*Outputs
Hello
*/

Example 3: Passing a first class function as an argument.

In the following example, we will pass the function greeting as an argument to another function sayGreeting that will call the greeting function.

function greeting() {
    return "Hello world";
}
 
 function sayGreeting(greeting) {
   console.log(greeting() );
 }


sayGreeting(greeting)

/*Outputs
Hello, world
*/

Conclusion

In this short tutorial you learn’t about first class functions.
To dive deeper into javascript functions check the following link.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x