The first-class object, sometimes referred to as a first-class citizen, is an object that supports every operation allowed on other objects. First-class objects can be stored in a variable, can be passed as an argument to the functions, can be returned by the function, can be stored in a data structure, can hold own properties and methods.
The first-class function is treated as an object, so it has state and behavior, and it can be passed as an argument to the function and returned from the function. In JavaScript, functions are objects, so this is the reason why the first-class function supports the same operations as objects.
// function definition
function logName(name) {
console.log(name);
}
// function invocation
logName('Lukas'); // logs 'Lukas'
// stored as variable
const logNameAlt = logName;
logNameAlt('Lukas'); // logs 'Lukas'
// first-order function (`callback`) being passed in as argument
function higherOrderFunction(callback) {
return callback; // first-order function being returned
}
const logNameHigher = higherOrderFunction(logName);
logNameHigher('Lukas'); // logs 'Lukas'
// stored in a data structure
const helpersArr = [logName];
const helpersObj = { logName };
helpersArr[0]('Lukas'); // logs 'Lukas'
helpersObj.logName('Lukas'); // logs 'Lukas'
// hold own property
logName.customProperty = 'Polak';
console.log(logName.customProperty); // logs 'Polak'
The higher-order function accepts a function as an argument, returns a function, or both. The higher-order function uses first-order functions, and the higher-order function is a first-order function themself.
The first-order function accepts a function as an argument.
The second-order function accepts a function that accepts a function.
Top comments (0)