A programming language is said to have first-class functions when functions in that language are treated like any other variable.
This means, in such a language, a function can be passed as an argument to other functions, returned by another function, and assigned as a value to a variable.
As a result, they exist in Javascript.
As a variable
1const welcome = () => console.log('hello world');2welcome(); //prints 'hello world'
As an Argument
1function CallPrintFunction (func) {23 if (typeof func === 'function') func();45}
The CallPrintFunction function would accept a function as a parameter and call it. Kindly note in javascript it’s better to double check if the argument is a function using typeof before calling it.
To use the above CallPrintFunction simply do the following
1const welcome = () => console.log('hello world');2CallPrintFunction(welcome);34// prints 'hello world'
Returned from another function
1function ReturnWelcome() {23return function welcome() { console.log('hello world');}45}
To use the ReturnWelcome function above i.e. call the function returned simply do the following
1ReturnWelcome()();
This one is pretty interesting since you can leverage closures to even enhance your returned function. Making another short post on closures soon I promise it would be straight forward.
That’s it Guys! . thanks for going through.