Mihai Vlăsceanu

Programmer, IT Geek

Functional programming in JavaScript - Part 1

Functional programming in JavaScript - Part 1

Hello everyone,

With this very first blog post I am starting a series of posts/tutorials on how to write JavaScript code in a functional programming way.

Introduction

First, you may ask "Why would you need to learn functional programming?". Well, that is a very good question. Learning functional programming will make you a better programmer. You will feel more secure about the quality of your code. Funcrional programming will make you write your apps with less bugs in less times. That sounds like wild promises, isn't it? Well, yes, but you will see how much value functional programming will bring to your coding life. Your code will be easier to reason about because your code will be easier to read, mainly due to code re-use.

Alright, hopefully I got your hopes high by now, so let's start.

Higher-order functions

The first aspect I am going to write about is also one of the essential features of functional programming: high-order functions. In general, in every functional language functions are values. That means that functions can be assigned to variables and, even better, passed into other functions, called higher-order functons. Here's example:

// Here is a normal function
function add(x, b) {
    return a + b
}

// Here we have an anonymous function assigned to a variable
var add = function(a, b) {
    return a + b
}

"But, what are higher-order functions good for?", you may ask. Well, they are good for composition. The fact that you can take one function and pass it to another function allows us to compose alot of small functions into a bigger function. Let's start with some examples.

One of the most basic and the most useful higher-order function in javascript is filter(f). The filter function that is used on an array. The function takes another function as an argument and it uses that function to return a filtered version of the same array. Let's start with some examples.

// Suppose we have the following array
var languages = [
    {name: 'Clojure', type: 'functional'},
    {name: 'Haskell', type: 'functional'},
    {name: 'Java',  type: 'object-oriented'},
    {name: 'Assembly', type: 'low-level'}
]

// Here's one way to filter the array in the non-functional way, with a for loop
var functionals = []
for(var i = 0; i < languages.length; i++) {
    if(languages[i].type === 'functional') {
        functionals.push(languages[i])
    }
}

// Here's how you can do it with filter()
var functionals = languages.filter(function(lang) {
  return lang.type === 'functional'  
})

A little explanation now. The function passed to the filter() function is called a callback function. What it basically filter() does is that it will go through each item in the array and call that function with the item as a parameter. What the callback function does is that it tells the program if that item should be left (or not) in the new filtered array. Therefore, the callback function should always return either true or false. In the end, filter will return the new array.

Now, if you read again the introduction of this post, I did state that you will write code faster. The piece of code above is a first example of that. If you notice, we did write less alot less code using filter() compared to the non-functional way. The reason we need less logic in our code is that when you write applications in small pieces they compose togheter. That allows you to re-use code all over the application. In the above example I wrote only 1 line of logic, the one telling if the item should be in the new filtered array. The actual logic of looping and creating the new array is handled by the filter() function for us. In this case, the callback function and the filter() function compose togheter.

Furthermore, we can also break the callback function into a variable, like this:

var isFunctional = function(lang) {
  return lang.type === 'functional'  
}
var functionals = languages.filter(isFunctional)

This is to show how well the functions compose togheter. They are completely de-coupled. We can re-use the same callback function to pass it to other functions.

Therefore, you can see how we broke down the for loop in the example above into 2 separate problems:

  • Checking if a language is functional
  • Creating a new array and pushing items into it

This allows us to debug

Conclusion

In this article I wrote about how you can write code with less bugs in less time by using functional programming. In JavaScript, functions are values. Given that, you can use that by dividing your code into small functions and then composing them togheter using higher-order function. As an example I used the filter() higher-order function to compare it with a regular for loop.

This is just the first post in this series and we are just scratching the surface. By following this series and learning functional programming you will be introduced to a whole new world of programming you probably did not know it existed. In the next part I will be writing about 2 other higher-order functions in JavaScript: map() and reduce(). Good luck!