JavaScript has first class function, when we say this, it means that, language treats functions like any other variable. What is like any other variable means? It means functions can be passed to a variable, functions can be passed as an argument to a function, functions can be returned by another function etc..
Lets look at whether a function in JavaScript is indeed a first class function.
- Assign a function to a variable.
const divide = function(x,y){ return x/y; };
Here we have a unnamed function, we assign it to a variable "divide" with the same syntax, that we used to assign a value to a variable.
- Pass function as parameter
const divide = function(x,y){ return x/y; };
const multiply = function(x,y){ return x*y; };
function calc(x,y, fun1, fun2){
let r1 = fun1(x,y);
let r2 = fun2(x,y);
console.log(`${x} * ${y} = ${r1}`);
console.log(`${x} / ${y} = ${r2}`);
}
calc(20,10, multiply, divide);
// 20 * 10 = 200
// 20 / 10 = 2
In the above code, focus on the "calc" function, it has four arguments, x, y, fun1, fun2
. By looking at he syntax of the variable r1 and r2 inside the calc function we can assume that variable fun1 and fun2 contain function code(functions). i.e. we are passing two functions as parameters. divide() method and multiply() method are passed for arguments fun2 and fun1 respectively. This can be confirmed when we look at the "calc" function call calc(20,10, multiply, divide);
. And we understand that functions can be passed as parameters.
- Return a function by another function
function calc(x,y, fun1, fun2){
let r1 = fun1(x,y);
let r2 = fun2(x,y);
console.log(`${x} * ${y} = ${r1}`);
console.log(`${x} / ${y} = ${r2}`);
return function() {
console.log(`${x} + ${y} = ${x + y}`);
console.log(`${x} - ${y} = ${x - y}`);
}
}
calc(20,10, multiply, divide)();
// 20 * 10 = 200
// 20 / 10 = 2
// 20 + 10 = 30
// 20 - 10 = 10
In the above code concentrate on the return statement of the calc function, it is returning a unnamed function, a function returning another function.
All these examples implies that JavaScript functions are indeed first class functions.
Lets look at one more example of first class function.
let fullName = function(fname, lname){
return (`${fname}${lname}`);
}
let randNum = function(year) {
let rNum = Math.round( Math.random() * year);
return rNum;
}
function createEmail(fn,ln, yr, fun1, fun2){
let full_name = fun1(fn,ln);
let num = fun2(yr);
console.log(`${full_name}_${num}@gmail.com`)
return function () {
let rdn1 = Math.random()*10
let rdn2 = Math.random()*100
let rand = Math.round( rdn1 * rdn2 )
return(`Password: ${ln}${rand}${fn}${yr}`);
}
}
let pass = createEmail("kiran", "raj", 1922, fullName, randNum)();
console.log(pass);
Top comments (0)