JavaScript has first-class functions, which are functions that can be:
We can assign a function to a variable. Then, the assigned function can be called using the variable name.
let printHi = function() {console.log("Hi I am function assigned to a variable so I am a first class Function");}printHi(); // calling the function with variable name
In the code above, we created an anonymous function and assigned the function to the printHi
variable. The function will be executed when this variable is called.
We can pass a function as an argument to other functions. When we call the function and argument, the passed function will be executed.
function printHi() {console.log("Hi I am function passed as an argument so I am a first class Function");}function executeFn(functionAsArgument) {functionAsArgument();}executeFn(printHi); // passing printHi function as an argument
In the code above, we passed the printHi
function to the executeFn
as an argument. The function passed as an argument is called the callback function.
We can return a function as a return value.
function getFunction() {return function(){console.log("I am function returned from another function so i am a first-class function")}}let fn = getFunction();fn(); // this will call the returned function
In the code above, we returned a function from getFunction
, stored the returned function in a variable, and then called the variable, which executed the returned function.
function multiply(mutiplyBy){return function(val){return mutiplyBy * val;}}let multiplyBy3 = multiply(3);let multiplyBy5 = multiply(5);console.log("Calling multiplyBy3 => ", multiplyBy3(10) );console.log("Calling multiplyBy5 => ", multiplyBy5(10) );
In the code above, we created a function multiply
, which:
multipyBy
The returned function:
multiplyBy
argument passed to the multiply
function