JavaScript Functional Programming
Functions are first class members in JavaScript, as they are simply a somewhat special type of object. They can be stored in variables, passed to other functions and returned from functions without any trouble. We'll see the full power of passing functions to other functions when we look at some of the complex data types later on.
Code example
const loudGreet = name => "GREETINGS " + nameconst silentGreet = name => "Greetings " + nameconst greeter = (greetFn, name) => {console.log(greetFn(name))console.log("How are you?")}greeter(loudGreet, "Kalam")// GREETINGS Kalam// How are you?greeter(silentGreet, "Kruppe")// Greetings Kruppe// How are you?
In the above example we have a greeter function that takes another
function as the first parameter and a string as the second
parameter. When we use the greeter function we can pass any function
that takes a string as an input and returns a string.
As we can see, the loudGreet and silentGreet functions are called
as we would expect them to be.
Code example: anonymous functions
It can be tedious to explicitly bind functions to constants or variables every time we want to pass them to other functions. Sometimes we just quickly want use pass a function without giving it a name. These functions are called anonymous functions.
The code example above could have been written like the one below instead.
const greeter = (greetFn, name) => {console.log(greetFn(name))console.log("How are you?")}greeter(name => "GREETINGS " + name, "Kalam")// GREETINGS Kalam// How are you?greeter(name => "Greetings " + name, "Kruppe")// Greetings Kruppe// How are you?