Why are JavaScript functions considered first class functions?

In Javascript functions are considered first class functions because

  • a) it can be assigned to a variable
  • b) it can be passed to a function without invoking
  • c) it can be returned from function

Assign to a variable

Function can be named function or anonymous function.

(named function)

let greetings = function hello(){
  console.log("hello");
}

greetings()
// hello

(anonymous function)

let greetings = function(){
  console.log("hello");
}

greetings()
// hello

Passed to a function

function multiply(a,b){
  return a * b;
}

function mathOperation(num1,num2, func){
  console.log( "Answer " + func(num1,num2) );
}

mathOperation(2,3,multiply);
// 6

Here we passed  a function multiply as an argument to function mathOperation when function mathOperation is invoked.

A function that gets passed to another function as an argument is called Callback function. In our example function multiply is a callback function.

Related article What the heck is callback?

A function that accepts a function as an argument or returns a function is called High Order function. In our example function mathOperation is a High Order function.

High order function and callback function are two important concept of functional programming.

Returned from function

function mathOperation(a,b){
  return function(){
    return a * b;
  }
}

mathOperation(2,3)();
//6

Here we have a function called mathOperation which returns anonymous function. To invoke returned function you have to used double parentheses ()().

function mathOperation is a High Order function because it returns a function.

We can also assign function mathOperation to a variable.

var x = mathOperation(2,3);

x();
// 6