JavaScript is a language that has first class functions, which in technical terms means that functions are so called first class citizens. In practice, that means that functions are treated like any other variable.
The following bullets represent important first-class function behavior:
- Functions can be assigned to variables
1 2 3 4 5 |
const printDenOf = function() { console.log("Den of Developers"); } // Invoke it using the variable printDenOf(); |
- Functions can be passed as arguments to other functions
1 2 3 4 5 6 7 8 |
function helloDenOf() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `helloDenOf` as an argument to `greeting` function greeting(helloDenOf, "Den Of Developers!"); |
- Functions can be returned from other functions
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function sayHello() { return function () { console.log('Hello Den of Developers!'); }; } // to invoke the function we have two ways //1 const myFunc = sayHello(); myFunc(); //2 sayHello()(); |
Just to be clear First Class Functions is a feature that a programming language have or does not have. There are no first class functions in practise its just a concept. But, they are a necessity for “Functional Programming” paradigm.
The fact that JavaScript has First Class Functions makes it possible for us to use and write Higher Order Functions.
What about Higher Order Functions?!
Well, Higher-order functions are functions that take other functions as arguments or return functions as their results (output). JavaScript comes with some built-in higher-order functions. You may already be using them, without realising that they are higher-order functions. Map, filter, and reduce are prime examples and make common patterns like transforming, searching, and summing much easier!
Ok, lets go trough one example.
1 2 3 4 |
let numbers = [3, 5, 2, 3, 4, 9]; let doubleNumbers = numbers.map(num => num * 2); console.log(doubleNumbers); // [6, 10, 4, 6, 8, 18] |
The above example uses an anonymous function as its callback. However, you can also do the same thing by creating and using a first class function.
1 2 3 4 5 |
let numbers = [3, 5, 2, 3, 4, 9]; let doubleNumbers = num => num * 2; let numsTimesTwo = numbers.map(doubleNumbers); console.log(numsTimesTwo); // [6, 10, 4, 6, 8, 18] |
Again, .map() is a high-order function. It allows a function to be passed as an argument. Higher-order functions allows you to write simpler and more elegant code. The map function is one of the many higher-order functions built into the language. sort, reduce, filter, forEach are other examples of higher-order functions built into the language.
Thats all folks, for now.