Almost everyone knows what a function is, and you can do a lot with functions!
A simple function:
function sayHello(){ console.log("Hello") } sayHello() // Hello
So, what exactly is a
First class function?
In short, the ability to assign a function to a variable, use a function as an argument for another function, or return a function from any block is an example of a
First class function
.Let's understand it better through examples!
- Storing in a variable: Functions can be stored in a variable.
let func = function() { return "Hello!"; };
- Returning as a result: Functions can be returned as a result from other functions.
function returnFunc() { return function() { return "Returned function!"; }; } let newFunc = returnFunc(); console.log(newFunc());
In our code, a function is returned within
returnFunc
, and we assigned it to a variable named newFunc
by calling returnFunc()
. Notice that ()
is used to invoke a function. In the last line, we call the returned function again using the newFunc()
variable.You can also call the returned function directly without assigning it to a variable by using double parentheses like
returnFunc()()
.- Passing as an argument: Functions can be passed as arguments to other functions.
function sayHello() { return "Hello "; } function greet(hiFunc, name){ console.log(hiFunc() + name); } greet(sayHello, "Ali");
As you can see in the code, the
sayHello()
function returns the word "Hello".The
greet()
function accepts hiFunc
as a function for the first argument and name
as a string for the second argument.Notice that we passed the
sayHello()
function as the first argument to the greet()
function in the last line, which is exactly the scenario where the First class function
concept applies. The second argument is a string.Be careful when working with these
()
parentheses. If you call the function with parentheses like greet(sayHello(), "Ali");
it will cause an error because the returned internal function won't be invoked!Now we know what a
First class function
is. 😎I hope the article was helpful! Thank you for your attention.