3 Methods for Getting Started with Functional Programming
April 7th, 2016 | By Jscrambler | 6 min read
What’s all the buzz over Functional programming?
If you’ve been keeping up with the hottest JavaScript trends, you may have come across the concept of Functional Programming.
In FP, Monads are an integral concept of Functional Programming. What are Monads? Easy, Monads in X is just a category of endofunctors of X, with product X replaced by a composition of endofunctors and unit set by the identity endofunctor.
You might be asking: “Huh?!”
Yes, that was English. No, you probably don’t need to understand the above, but definitions like this are plentiful when you read about FP.
Ignore Monads for now. They certainly don’t facilitate the understanding of Functional Programming, but they are a part of Functional Programming.
Think of Functional Programming as both a style of writing JavaScript and a programming paradigm.
Functional Programming: What is it? Why should I care?
Functional Programming treats data and behavior as different things that should be kept separate for clarity in addition to reducing bugs in your applications. To program functionally would mean that you adhere to a few essential rules:
Your functions are not dependent on context and should have no side effects. “Side effects” are unwanted or unexpected consequences from your code writing style or the fact you have mutable data types. Your functions cannot modify anything outside of themselves. They don’t depend on the external state of the function. In other words, anything that happens in a function stays in a function.
Your functions should also be built to allow them to be composed into other functions in the same or even another program. Don’t change the state of your system, and use immutable data. “Pure” functions always return the same result for a given input. A pure function with no side effects will always have the same result for any input with no observable effect. Hence FP functions are “pure”. Aside from being part of a special elite, developers programming with pure functions can count on a reliable output.
How can I use it?
By following functional programming paradigms, we can avoid headaches during development by ensuring we follow a consistent style.
In JS, functions are first-class objects. They can be passed or stored in an array, whatever you do with a value you can do with a function.
Functions are treated as building blocks, those self-contained building blocks can create bigger building blocks. Whereas in other programming styles like OOP, each building block may have an unintended consequence or result. If the functions were pure and independent of other functions you wouldn’t have to worry about the volatility of said functions.
Enter “higher-order functions”. Higher-order functions are just functions that can take other functions as arguments or return them as a result.
Composition is all about using our higher-order function building blocks to construct a larger system. Take one block, use it to compose a bigger block, and so on. Composing with pure functions reduces the complexity of your application and lets you reason about your code easily.
The following are some higher-order “pure functions” built into vanilla JavaScript commonly used when following a functional programming style. These practical examples will give you a better idea of what functional programming is, without the abstracted and confusing terminology.
Map
The map is a function on the array object and is considered a list transformation. Some consider maps to be their default bread-and-butter iterator.
You would use the map to transform a list of elements from one type to another by iterating and modifying each item in that list into a new object.
Map will include all items and expects a transformed object which it will use to create a new array.
Check the code below
//our array of data
var cars = [{
make: 'Nissan',
model: 'leaf'
}, {
make: 'Chevrolet',
model: 'bolt'
}, {
make: 'BMW',
model: 'i8'
}, {
make: 'Tesla',
model: 'model X'
}];
//our pure function:
function getCarModel(car) {
return car.model;
}
var models = cars.map(getCarModel);
console.log(models);
function getCarModels() {
var models = []
for (var i = 0; i < cars.length; i++) {
models.push(cars[i].model)
}
return models;
}
//filthy impure version:
var models = getCarModels();
console.log(models)
Not only is the pure function less code but it’s pretty obvious to reason about the result just by reading function. Keep in mind, that all of the used methods will return a new copy of the data they’re modifying.
Filter
Filter is a method on Array objects that accepts another function as an argument. It then uses the argument to return a new “filtered” version of that array and throws the original list away.
Here’s an example
//our data
var cars = [{
make: 'Nissan',
model: 'leaf'
}, {
make: 'Chevrolet',
model: 'bolt '
}, {
make: 'BMW',
model: 'i8'
}, {
make: 'Tesla',
model: ‘model X '}
];
//Pure:
function isI8(car) {
return car.model === ‘i8’;
}
var i8s = cars.filter(isI8)
//Impure:
function getI8Cars() {
var i8s = []
for (var i = 0; i < cars.length; i++) {
if (cars[i].model === ‘i8’) {
i8s.push(cars[i])
}
}
return i8s;
}
var i8s = getI8Cars();
Reduce
Reduce is the grandaddy of list transformations. It’s so versatile that you can create a map and filter with reduce. It’s a method you can fall back on if none of the other functions fit your needs. For example, if we wanted to summarize all of the amounts in the example array, we’d be able to use Reduce.
Reduce is a function on the array object, that takes a callback function and a starting value as a second argument. It then “reduces” the list to a single element as a new object.
Here’s a basic example
//our data
var orders = [{
amount: 187
}, {
amount: 300
}, {
amount: 415
}, {
amount: 435
}];
//Pure function
function calcSum(sum, order) {
return sum + order.amount;
}
var totalAmount = orders.reduce(calcSum, 0);
console.log(totalAmount);
//Compare to the “impure” function
function totalAmount() {
var result = 0
for (var i = 0; i & lt; order.length; i++) {
result += orders[i].amount
}
return result;
}
var totalAmount = result;
console.log(totalAmount)
Numerous functions that qualify as “pure” exist to help us achieve the goal of bug-free functional code. Map, Filter, and Reduce are available in plain ol’ JS but there are entire libraries at our disposal.
Polyfill libraries like Lodash.js and Underscore.js provide immutable data types and functional methods for browsers that don’t support them.
The Functional Programming approach intends to make our code easier to reason about. By designing our systems functionally we don’t have to worry about the state and rendering; instead, we focus on the business logic.
Let’s now take a look at Functors.
Functor
Functors are objects that have/implement a map method. One good example of this is the array in JavaScript.
There are three main principles that apply to functors, let’s look at them using the javascript map method as an example.
Transformation of contents – The map function takes the contents of the array and uses the callback passed to the map to transform the contents into something else.
Maintain structure – Functors are also known by this property, they maintain the structure of the original content so, regarding JavaScript, the array that is mapped returns an array with the exact same size.
Returns a new functor – The return value of the array.map is an array which for instance and as told before is a functor so we can now confirm that the array is a Functor.
So now we have enough to understand the Monads.
Monad
Monads are a type of functors that have/implement a method that handles wrapped values and returns the same wrapped value.
One example of that is the then method in JavaScript Promises. This method takes a promise, unwraps its value, does the processing, and returns another promise.
As you can see, the JavaScript language is taking steps into the functional programming concepts, and some of them you may be using on a daily basis even if you are not familiar with them.
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
A Programmer’s Guide to React Router
The React Router library provides a flexible and simple way to achieve dynamic routing in React.js apps. In this article, we explore it with a demo app.
July 2, 2019 | By Camilo Reyes | 5 min read
Creating a Functional Component in Vue.JS
In this article, you will learn how to create functional components in Vue.js.
September 30, 2022 | By Jscrambler | 4 min read