What is a first class function in JavaScript?
In JavaScript, functions are first-class citizens, along with numbers, strings, and other data types. You can assign functions to variables, pass them as arguments to other functions, and return them from functions.
// Assign a function to a variable
const sayHello = function() {
console.log("Hello, World!");
}
// Pass the function as an argument to another function
const callFunction = function(fn) {
fn();
}
callFunction(sayHello); // Outputs: "Hello, World!"
// Return the function from a function
const createGreeting = function() {
return sayHello;
}
const greeting = createGreeting();
greeting(); // Outputs: "Hello, World!"