First-Class Functions:
In programming languages with
first-class functions, functions are treated as values and can be assigned to variables, passed as arguments to other functions, and returned as values from functions. Essentially,
first-class functions allow functions to be treated like any other
data type.
Here's an example in JavaScript:
// Assigning a function to a variable
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
// Passing a function as an argument
function higherOrderFunction(func) {
func("John");
}
higherOrderFunction(greet); // Output: Hello, John!
In the example above, the function is assigned to the variable `greet`. Then, `greet` is passed as an argument to the
`higherOrderFunction`, which in turn calls the function with the provided argument.
Higher-Order Functions:
A
higher-order function is a function that takes one or more functions as arguments or returns a function as its result. In other words, it operates on functions, either by accepting them as arguments, returning them, or both.
Here's an example in JavaScript:
// Higher-order function
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const multiplyByTwo = multiplyBy(2);
console.log(multiplyByTwo(5)); // Output: 10
In the example above, the
`multiplyBy` function is a higher-order function that takes a factor as its argument and returns an inner function. The inner function, when called, multiplies the provided number by the factor. The
`multiplyBy` function can be considered higher-order because it returns a function as its result.
Conclusion:
In summary, the main difference between
first-class functions and
higher-order functions is that first-class functions treat functions as values, allowing them to be assigned, passed, and returned like any other data type. Higher-order functions, on the other hand, are functions that operate on functions, either by accepting them as arguments or returning them as results.