First Class Functions In Javscript
November 18, 2021

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) {
2
3 if (typeof func === 'function') func(); 
4
5}

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);
3
4// prints 'hello world'

Returned from another function

1function ReturnWelcome() {
2
3return function welcome() { console.log('hello world');}
4
5}

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.


Adeyemi Adekorede
Adeyemi Adekorede
I'm passionate about technology and currently work remotely from Lagos (Nigeria) as a software engineer at MindRight Health (New jersey, USA). You can support my work or reach out by connecting with me.
linkedin icontwitter icongithub icon