1

Functional Programming in JavaScript

Reading Time: 3 minutes

Functional programming is a declarative paradigm because it relies on expressions and declarations rather than statements & it uses functions. The following are the basic rules it should follow

  • Pure functions
  • Higher order functions
  • Immutability (Unchangeability)
  • No Side effects

Lets have look at each every rule in detail

Pure functions

Functions which always returns same results for the same given arguments/inputs with no side effects.

function SuffixNew(usersArray) {
    var copiedArray = [];
    for (var i = 0; i < usersArray.length; i++) {
        copiedArray.push(usersArray[i] + ' New');
    }
    return copiedArray;
}

The above function `SuffixNew` will return new array with a word ‘New’ suffixed. If you notice parameter passed & global variables are not modified (immutable) & it doesn’t do anything else (no side effects) it just Suffix’s the word ‘New’.

var users = ['a', 'b', 'c', 'd'];
var usersCopyA = SuffixNew(users);

console.log(users);
console.log(usersCopyA);

If you execute the same function again with the same set of parameters passed you would get same results.

The below is the simplified version using `map` function. See how 7 lines of code previously used are replaced with just a single line of code

var users = ['a', 'b', 'c', 'd'];
var usersCopyB = users.map(u => u + ' New');

console.log(users);
console.log(usersCopyB);

Higher Order function

A function that does at least one of the following

  • takes one or more functions as arguments/parameters
  • returns a function as its result
function Twice(digit) {
    return digit * 2;
}
//const Twice = (digit) => digit * 2;

function Thrice(digit) {
    return digit * 3;
}
//const Thrice = (digit) => digit * 3;

function Calculate(fn, val) {
    return fn(val);
}
//const Calculate = (fn, val) => fn(val);

console.log(Calculate(Twice, 2));//4
console.log(Calculate(Thrice, 2));//6

In the above example a function is passed as a parameter toCalculate function

function IsOlderThan(ageLimit) {
    return function (age) {
        return age > ageLimit;
    }
}

var IsOlderThan18 = IsOlderThan(18);

console.log(IsOlderThan18(22));//true
console.log(IsOlderThan18(6));//false

Here function IsOlderThan returns a function as result

Benefits of Functional Programming

  • Greater Predictibility
  • Improved Testability
  • Easier Extensibility

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.