In JavaScript functions are treated as First-class Function when a function can be assigned as a value to variable or it can be passed as arguments to other function or can be returned by another function.
Example: Assign a function to variable
const name = function() {
console.log("Rishi");
}
name(); // invoking it using variable
// Rishi
Note: You can name function, still you can invoke by using variable.
Example: Pass a function as an Argument
function hello() {
console.log("Hello, ")
}
function greetingUser(helloMessage, user) {
console.log(helloMessage() + user);
}
//pass hello as argument
greetingUser(hello, "Rishi");
// Hello, Rishi
Example: Return a Function
- Using Variable
const name = function() {
return function(){
console.log("Rishi");
}
// invoking function using variable
const myName = name();
myName();
- Using double parentheses
function name() {
return function(){
console.log("Rishi");
}
// invoking function using double parentheses
name()();