What is a first-class function in JavaScript?

JavaScript has first-class functions, which are functions that can be:

  • Assigned to variables
  • Passed as arguments to functions
  • Returned from functions

Assigning a function to a variable

We can assign a function to a variable. Then, the assigned function can be called using the variable name.

let printHi = function() {
console.log("Hi I am function assigned to a variable so I am a first class Function");
}
printHi(); // calling the function with variable name

In the code above, we created an anonymous function and assigned the function to the printHi variable. The function will be executed when this variable is called.


Passing a function as an argument

We can pass a function as an argument to other functions. When we call the function and argument, the passed function will be executed.

function printHi() {
console.log("Hi I am function passed as an argument so I am a first class Function");
}
function executeFn(functionAsArgument) {
functionAsArgument();
}
executeFn(printHi); // passing printHi function as an argument

In the code above, we passed the printHi function to the executeFn as an argument. The function passed as an argument is called the callback function.


Returning a function

We can return a function as a return value.

function getFunction() {
return function(){
console.log("I am function returned from another function so i am a first-class function")
}
}
let fn = getFunction();
fn(); // this will call the returned function

In the code above, we returned a function from getFunction, stored the returned function in a variable, and then called the variable, which executed the returned function.


Another example

function multiply(mutiplyBy){
return function(val){
return mutiplyBy * val;
}
}
let multiplyBy3 = multiply(3);
let multiplyBy5 = multiply(5);
console.log("Calling multiplyBy3 => ", multiplyBy3(10) );
console.log("Calling multiplyBy5 => ", multiplyBy5(10) );

In the code above, we created a function multiply, which:

  • expects an argument multipyBy
  • returns a function

The returned function:

  • expects one argument
  • returns the multiple of the passed argument with the multiplyBy argument passed to the multiply function

Free Resources