Functional programming in Javascript - First class & higher order functions
Introduction
First class functions and higher order functions. Terms that if you are new to JavaScript or functional programming may sound scary.
No need to worry, it’s enough to understand a couple of simple concepts and they will soon be your friends.
Sometimes, people talk about them as if they were the same thing but they are not. They are closely related but there is a subtle difference and this usually generates some confusion.
First class functions
In JavaScript functions are first class citizens. This can be translated into:
Functions are values.
What does it actually mean? Let’s see it with an example.
Here is a simple function that logs ‘Hello world!':
|
|
As we said functions are values so we can assign them to variables:
|
|
And as any other value we can pass it to other functions as argument.
|
|
To recap, first class functions can be assigned to variables and be passed around.
Higher order functions
Higher-order functions are functions that work on other functions.
In other words, Higher-order functions are functions that can take one or more functions as arguments and can also return a function as result.
Functions that are passed to other functions are often referred to as callback functions because they are called by the function that receive them as argument, the higher order function.
Higher-order functions are a great thing because allow us to write code in a declarative style making it simpler to read and understand.
JavaScript comes with many higher-order functions built in such as map
, filter
, forEach
etc… let’s see an example to understand how they can simplify our lives.
Given the following array of numbers let’s find all the even numbers.
|
|
Here is how we could achieve it without higher-order functions:
|
|
Now the same result but using higher-order functions.
All we need to do is to use the filter
function which will iterate over our array and call the anonymous function we passed for each number.
|
|
Making also use of first-class functions we could even write it in a more readable way.
|
|
Conclusion
To sum it up, the first-class concept has to do with functions in a programming language context while the higher-order concept is more about the mathematical sense of it.
In other words the support of first-class functions in a language implies the presence of higher-order functions, but not the other way round.
JavaScript supports both, allowing us to write simpler and more elegant code, and that’s why they are a fundamental pillars of functional programming.