
A first-class function in JavaScript means that functions are treated like any other value. This means functions can:
- Be assigned to variables.
- Be passed as arguments to other functions.
- Be returned from other functions.
- Be stored in data structures 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) {
return fn(value);
}
const square = (num) => num * num;
console.log(executeFunction(square, 5)); // Output: 25Example: Returning a function from another function
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
console.log(double(10)); // Output: 20Since functions in JavaScript can be assigned, passed around, and returned just like any other value, they are considered first-class citizens in JavaScript. 🚀
