In JavaScript, functions are first class objects, meaning that they can access and be passed into function. But what does that really mean? How is a first class function different from a higher order function or a callback function?
These terms aren't mutually exclusive, but I think it's important to explore the nuances.
First class vs higher order vs callback
-
First class: In JavaScript, functions are treated as first-class objects. I already discussed why functions are objects in this post. A first class object is one that is treated like a variable, meaning they can be:
- stored to a variable
- passed as an argument (as a callback)
- returned from a function
Higher order function: This refers to a function that accepts a function as an argument or returns a function as its result
Call back function: A callback function is one that gets passed as an argument to a function
Just remember:
- A higher order function can accept a callback function as an argument
- Both higher order and callback functions are first-class functions. This is because JavaScript treats functions as first class objects
Because these 3 terms are so intertwined, I've included the links below that discuss all three, instead of one post for each term:
- Any difference between First Class Function and High Order Function link...
- Functional JavaScript: What are higher-order functions, and why should anyone care? link...
- Closures, first-class functions, and higher-order functions link...
let arr = [1,2,3,4,5]
const firstClass = (num) => {
return num * num
}
const higherOrder = (array, callback) => {
let newArray = []
for(let i = 0; i < array.length; i++){
newArray.push(callback(array[i]))
}
console.log(newArray)
}
higherOrder(arr, firstClass) // [ 1, 4, 9, 16, 25 ]
Still confused? Leave a comment to let me know. I'm happy to explain further!