First Class Function:
Apr 17, 2024
#3 Javascript Series
In JavaScript, functions are treated as first-class citizens, which means that functions can be used like any other value, such as being passed as an argument, assigned to a variable, or returned as a result of a function.
A function assignment to a variable
function add (a,b){
return a+b;
}
const sum = add;
console.log(sum(2,3));
Output: 5
A function passed as an argument to another function
function greet (name, fn){
fn (name);
}
greet ("Deep", (nm)=>{
console.log(`Hello, ${nm}`);
});
Output: Hello Deep
A function returning function as a result
function HOF(){
return function(){
console.log("Hello");
}
}
const LOF = HOF();
LOF();
Output: Hello