Sign in
Log inSign up

First Class Function && Higher Order Function ft. js

sathithya yogi's photo
sathithya yogi
·Apr 30, 2022·

2 min read

First Class Function

A programming language is said to have first-class functions , if the function in that language is treated as a variable and the function are called first class citizen

The function can be assign to a variable, pass as a argument to a function, and can able to return a function.

const getAge = function (yearBorn, currentYear){
         console.log(yearBorn - currentYear)
}
    // pass arguments to the getAge function
    getAge(1996, 2022) 
    // 26

Above, the function is assigned to a variable and invoked at the end. lets see another example,

const getDetails = {
  firstName : "Rika",
  lastName: "Ma",
  yearBorn:1996,
  getAge : function(){
      console.log(new Date().getFullYear() - this.yearBorn);
  },
  getFullName: function(){
        console.log(this.firstName + " " + this.lastName);
  }
}

  getDetails.getFullName(); 

  // Rika Ma

In the above example, we assign getAge() and getFullName() function as a property of a getDetails object.

Higher Order function

when a function returns functions or accepts a function as an argument is called higher-order function, it is possible because of first-class function.

Higher-order functions are functions that work on other function, which they take one or more function as an arguments and it can also return a function

function calculate(param1, param2, fn){
  return fn(param1,param2);
}

function add(a,b) {
  return a+b;
}

function subtract(a,b){
   return a-b;
}

// example 1
const addResult = calculate(1,4,add);
console.log(addResult); // 5

// example 2
const subResult = subtract(6,1,add);
console.log(subResult); // 5

In the above code, we have a function called calculate which takes three params and return a third param with the first two params as an argument of it. and we declared two function which do different operations, add and subtract functions are pure function.

we call a function as Pure function when it returns same result while passing same input, despite of calling n number of times. and it does not have any side effects.

Here side effects refers to changing the value of a variable not in that functional scope or in the global scope.

If we pass a function as an argument to another function then the function that we pass as an argument is called callback function

In the 1st example we pass add function to calculate function where the calculate function returns the add function with 1 and 4, then add function returns a value by adding two-parameter, this is the example for higher-order function which get function as a argument and return a function.

In js higher order functions can be seen in many places like map, filter, reduce etc... which accept a callback function and returns a value.