How to write First-class functions using Javascript

First-class functions are the feature of functional programming language. Not all programming languages support first-class function implementation. Javascript is a functional programming language and it supports the first-class function implementation.

Learn more: What is first-class function

The main function of a first-class function is – a first-class function can be passed through another function as an argument or value. First-class functions also can be assigned to a variable.

And probably we can execute the output of the variable by calling the variable name in which variable the function is assigned to.

Javascript First-class Function

In Javascript, a first-class function can be declared using three different methods. Although they have individual definitions, they are obviously considered as the first-class function.

  • Passing functions as an argument
  • Passing functions using variables
  • Returning a function using another one

Let’s implement them by example(s)

Passing function as an argument

First we will declare a function and then we will pass the variable through another declared function.

Example:

functionfirstName() {
   return "Mehrab ";
}
function passFunc(myName, name) {
  document.write(myName() + name);
}

passFunc(firstName, "Mohul!");

Program output:

Mehrab Mohul!

Passing functions using variables

We will declare a variable using var keyword the as a value we will put a function in that variable. Then finally we will pass the function for execution phase by calling the variable name with a parentheses ()

Example program:

var myVar = function() {
   document.write("Hello, PrograCoding!");
}
// evaluate the function by calling the variable
myVar();

Program output:

Hello, PrograCoding!

This type of function is also called Anonymous Function

Returning a function from another function

To implement using this method, we will add a function to a return value inside another function. Then finally to invoke or call the function output we can use two methods, first on is, use double parentheses after the function name eg: myFunc()().

And the second method is, take advantage of another variable. And we will assign the function as a value to the newly declared variable. Finally we will call the variabale name to execute. See example below:

Example program:

function myName() {
   return function() {
      document.write("Mehrab Mohul");
   }
}

//Way 1: double parentheses method.
myName()();

//Way2: taking help from another variable
var myFunc = myName();
myFunc();

Program output:

Mehrab Mohul Mehrab Mohul

A function returns another function, this method is called Higher-Order Function

Tags