Functional Programming with Javascript | Introduction

Share on Facebook0Tweet about this on Twitter0Share on LinkedIn3

 

You might have heard that there are some developers talking about how cool functional programming is. Robert C Martin (also know as Uncle Bob  and is a world famous developer) predicts functional programming is the future in some of hispresentations. So, I think it’s worth it to explore functional programming concepts. Some pure functional programming languages areClojure,Haskell etc.

 

In this post, you will learn:

1. What is functional programming?

2. Why functional programming with Javascript?

3. Functional programming concepts with Javascript.

4. Comparing Imperative Vs Object-Oriented Vs Functional Programming Paradigms.

 

What is Functional Programming?

Functional Programming is a paradigm or style to structure your code in a functional way, meaning you use functions for everything. In a functional programming paradigm, functions are the kings. We can write functional programming with vanilla JavaScript because JavaScript is very flexible when it comes to using different paradigms.

Why Functional Programming?

There are other paradigms such as Imperative and Object-Oriented that you might think would be better. However, I think Imperative is a very step-by-step approach and could cause a lot of global scoping and readability issues. On the other hand, working with Object-Oriented Javascript is sometimes tricky and confusing especially when it comes to dealing with “this” and “bind” keywords. Things could be simpler and that is where functional programming comes to the rescue.

 

Most of the time, adding a functional programming structure would make your code more maintainable and readable as your project is getting larger. It does not mean that other paradigms are completely bad  Each one has their own pros and cons. However, thinking of a functional way would help your code, which will likely have some bugs or errors, be more elegant or easy to understand. I hope you’re convinced now that functional programming would have some interesting concepts to learn.

Functional Programming Concepts with Javascript

1. Everything you write should be inside a function literal. Functions are values and can be assigned to variables like Strings, Ints etc.

 

Normally, you can declare a function and invoke it after in many different languages similar to the code below:

 

function rootSquare(num) {
 return num * num;
}
var result = rootSquare(8) ;
console.log(result); // 64

In Javascript, you can write an anonymous function like the one below. In this code example, you can assign a function literal to a variable and use it wherever you want. This can only be done in Javascript. Now you know how functions can be written in Javascript in different ways.

 

var rootSquare = function(num) {
 return num * num;
}
var result = rootSquare;
var result1 = result(9)
console.log(result1); // 81

 

2. Always write pure functions. Pure functions take an input and compute something and then returning either a value or another function. Pure functions should do just that. If the function is using the variable that is declared outside of the function block to compute something to return, that function is not considered a pure function. We can avoid the side effect of worrying about the changing state of any variable.

 

3. Abstract functions in your code. Decouple your functions as much as possible in order to reuse the function anywhere in your code.

 

4. Higher-order functions are the functions that return other functions and compose small functions together in order make a bigger function that does exactly what you want that function to return. Always use higher-order functions instead of integrating a list using “for”.  There are a few array object methods in Javascript such as Map, Filter, Reduce etc. Before using them, I want to show the customized higher-order function in the code sample below.

 

function composeName(firstName) {
    return function(lastName) {
        return firstName + " " + lastName;
    }
}

var yourFirstName = composeName("Ramu");
var yourFullName = yourFirstName("Sundar");

console.log(yourFullName); // Ramu Sundar

 

If you want to know more about higher-order functions, check out my other article Functional Programming with Javascript | Higher-Order Functions.

 

5. Always make immutable variables. You can achieve this by having a persistence data structure using Mori or immutable.js libraries to open the features such as linked list, trees, path dealing to help with efficiency. I will not be covering how to create a persistence data structure using those libraries as it’s not the scope of this post.

Comparing Imperative Vs Object-Oriented Vs Functional Programming Paradigms

Let’s start with an Imperative Paradigm. The code example below takes an input string and converts it into an array and removes any extra spaces. Then it sorts the array and returns a sorted array. I am using a simple example so that it gets to the point and is easier to follow.

 

var output; // final output

function getInput() {

  var inputText = document.getElementById("input_value").value;
  console.log( sortFruits(inputText)); // Sorted Frutis Array 
};

function sortFruits(inputText) {
  
  var counter;
  output = [];
  var fruitsArray = inputText.split(",");

  for(var counter = 0; counter < fruitsArray.length; counter++) {
    output.push(fruitsArray[counter].trim());
  }

  return output.sort();
}

document.getElementById("main_button").onclick = getInput;

 

An imperative paradigm is fine to use until your coding gets bigger and it becomes messy. Let’s try the same functionality with the Object-Oriented paradigm.

 

(function() {
 "use strict";
 var SomeText = function(text) {
 this.text = text;
 };
 SomeText.prototype.removeSpace = function(str) {
 return str.trim();
 };
 SomeText.prototype.sortArray = function() {
 var result = [];
 var fruitArray = this.text.split(",").sort();
 for (var counter = 0; counter < fruitArray.length; counter++) {
 result.push(this.removeSpace(fruitArray[counter]));
 }
 return result.sort();
 };

 document.getElementById("main_button").addEventListener("click", function(e) {
 var fruitsString = document.getElementById("input_value").value;
 var newText = new SomeText(fruitsString);
 console.log(newText.sortArray());
 });
}());

The Object-Oriented Paradigm has a better structure than the Imperative Paradigm but there is still a lot of code for a simple functionality. Let’s try the same functionality with my favourite  Functional Paradigm.

 

(function() {
 "use strict";
 var removeSpace = function(item){
 return item.trim();
 }
 var sortFruits = function(fn, str) {
 return str.split(",").map(fn).sort();
 };
 document.getElementById("main_button").addEventListener("click", function(e) {
 var fruitsString = document.getElementById("input_value").value;
 console.log(sortFruits(removeSpace, fruitsString));
 });
}());

 

As you can see, the Functional Paradigm is well structured and has less code. When you look at the code, you can see all the syntax similar to the other two paradigms. However, you can see a new keyword “map” –  unless you have worked with functional programming before. The keyword “Map”  is one of the higher-order functions. If you want to dive deep into higher-order functions, check out my other blog.

 

In conclusion, no one paradigm is better than the other. Each one solves a different issue depending on what kind of problem you have. However, most of the time, I use the functional way to write code in Javascript because it makes more sense to me in most of the scenarios.

 

There you have it! I hope you enjoy!  Feel free to check out and enroll in our online Javascript and JQuery course. Contact us for one FREE virtual online class from anywhere.

 

Leave a comment if you have any questions or suggestions. If you like it, don’t forget to share it with your friends. Thanks for reading!

 

Share on Facebook0Tweet about this on Twitter0Share on LinkedIn3

About the author
Raja Thangarasu

Raja loves building Web and iOS Applications. He is always curious to explore latest technologies and concepts. He's working as a UI Developer and he is teaching various technologies at SoftAuthor. He likes to write blogs and create youtube videos when he has time to share his knowledge to the world. Visit his website for more information about him.

Sign up for our blog updates and newsletters!


100 % privacy. I hate spam as much as you do!

  • User X

    dafuq mean, excellent explanation. I’ve been completing free code camp’s javascript exercises and there’s a lot of functional programming since they teach examples with reduce, filter, map, etc…
    I’ll dig more into your blog (y)