What are first-class vs higher-order functions in JavaScript?

First-class functions

First-class functions are functions that are treated as variables. They can also be parsed into other functions as arguments.

In JavaScript, functions are treated as values or just another type of object.

Code

Example 1

The output in the program below is stored in a variable called Person.

const Person = {
play:(name) => {
return `Hey ${name} is playing`;
},
dance:(name) => {
return `${name} can dance`
},
walk:(name) => {
return `I am sure ${name} can walk `
},
}
console.log(Person.play("Chibueze"));
console.log(Person.dance("Chibueze"));
console.log(Person.walk("Chibueze"));

Higher-order functions

Higher-order functions are functions that take other functions as arguments (callbacks) or return functions as their results.

This concept is used a lot in JavaScript.

Higher-order functions include:

  • map
  • sort
  • filter

Example 2

We created a named conditional function, then parsed it as an argument to our higher-order function to be used as a conditional each time we are looping through the array values.

//The map function takes other function as argument
function doubleElements(x){
return 2*x;
}
let DoubleResult=[1,2,3,4,5,6].map(doubleElements)
function filterElemLesThanTwo(x){
return x<2
}
let ResultLessThanTwo=[1,2,3,4,5,6].filter(filterElemLesThanTwo)
console.log(DoubleResult)
console.log(ResultLessThanTwo)

Conclusion

First-class functions are JavaScript functions that can behave like variables.

They can also be parsed as arguments to higher-order functions.

Higher-order functions are functions that return a function or take in a function as an argument.