Functional Fundamentals: Higher Order Functions

This is part two in my series on functional programming concepts. Last time, we learned about pure functions.

This time, we are going to learn about higher order functions. This is the feature that makes functional programming possible.

You know what a function is. But, what does higher order mean?

Function In A Function

A higher order function is one that takes a function as a parameter, and returns a new function as a result.

Here is an example:

function getPrice() {
	return 10;
}

function half(func) {
	return function() {
    	return func() / 2;
    };
}

var halfPrice = half(getPrice);
halfPrice(); // 5

So What?

Higher order functions allow us to feed one function into another many times over, building up a chain of operations to which can be triggered with a single function call.

Take a moment to appreciate the power of this.

Now you are able to construct things like:

function getPrice() {
	return 10;
}

function half(func) {
	return function() {
    	return func() / 2;
    };
}

var halfPrice = half(getPrice);
halfPrice(); // 5

function discount(func) {
	return function() {
    	return 0.80 * func();
    };
}

var discountHalfPrice = discount(halfPrice);
discountHalfPrice(); // 4

Ofcourse this is a contrived example, but the idea is that you can perform a series a small operations using a single function call. Eventually, this could trigger your entire program.

Next, we will look at how we can extend this idea to combining multiple functions at the same time - with compose.