First-class function

A programming language is said to have first-class functions if it treats functions as first-class citizens.

A function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

Assign a function to a variable:

const foo = function() {
   console.log("foobar");
}
// Invoke it using the variable
foo();

We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses () at the end.

Pass a function as an Argument:

function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");

We are passing our sayHello() function as an argument to the greeting() function, this explains how we are treating the function as a value.

Return a function:

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}

We need to return a function from another function - We can return a function because we treated function in JavaScript as a value.

Last updated