A first-class functionin JavaScript means that functions are treated like any other value. This means
functions can:
1. Be assigned to variables.
2.
Be passed as arguments toother functions.
3.
Be returned from otherfunctions.
4.
Be stored in datastructures like arrays and objects.
Example: Assigning a function to a variable
const greet = function(name) {
return
};
console.log(greet("Prakash")); // Output:Hello, Prakash!
Example: Passing a function as an argument
function executeFunction(fn, value) {
returnfn(value);
}
const square = (num) => num * num;
console.log(executeFunction(square, 5)); // Output:
25
Example: Returning a function from another function
function multiplyBy(factor) {
returnfunction(number) {
return number * factor;
};
}
const double = multiplyBy(2);
console.log(double(10)); // Output: 20
Since functions inJavaScript can be assigned, passed around, and returned just like any other
value, they are considered first-class citizens in JavaScript. π
functions can:
1. Be assigned to variables.
2.
Be passed as arguments toother functions.
3.
Be returned from otherfunctions.
4.
Be stored in datastructures like arrays and objects.
Example: Assigning a function to a variable
const greet = function(name) {
return
Hello, ${name}!;};
console.log(greet("Prakash")); // Output:Hello, Prakash!
Example: Passing a function as an argument
function executeFunction(fn, value) {
returnfn(value);
}
const square = (num) => num * num;
console.log(executeFunction(square, 5)); // Output:
25
Example: Returning a function from another function
function multiplyBy(factor) {
returnfunction(number) {
return number * factor;
};
}
const double = multiplyBy(2);
console.log(double(10)); // Output: 20
Since functions inJavaScript can be assigned, passed around, and returned just like any other
value, they are considered first-class citizens in JavaScript. π
π1