April 7, 2016

3 Methods for Getting Started with Functional Programming

By Jscrambler | 6 min read

3 Methods for Getting Started with Functional Programming

What’s all the hullabaloo over Functional programming?

If you’ve been keeping up with the hottest JavaScript trends out there 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 are just a category of endofunctors of X, with product X replaced by composition of endofunctors and unit set by the identity endofunctor.

You might be asking yourself “huh?!”

funny gif

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 make understanding Functional Programming any easier but they are indeed a part of Functional Programming. In the effort of keeping it real, think of Functional Programming as both a style of writing JavaScript and a programming paradigm.

What is it and 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 in a functional way 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” being unwanted or unexpected consequences as a result of your code writing style or the fact you have mutable data types. Your functions cannot modify anything outside of themselves and 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 in a way that allows them to compose into other functions in the same or even another program, don’t change the state of your system and use immutable data. “Pure” functions are those that 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 being “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 just 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 either 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 more easily.

The following are some higher-order “pure functions” built into vanilla JavaScript that are 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

Map is a function on the array object and is considered a list transformation. Some consider map to be their default bread and butter iterator. You would use 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, all of the used methods will return a new copy of the data they’re modifying.

Book a Jscrambler Demo

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 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 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 makes 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 into 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.

As a final word, don't forget to download our free data sheet on JavaScript Security Threats, which provides an overview of the most relevant attacks and how to prevent them.

Author
JscramblerThe 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 Posts

Subscribe to our weekly newsletter

Learn more about new security threats and technologies.

I agree to receive these emails and accept the Privacy Policy.