Functional Programming in JavaScript

Nazmul Hoque
Rokomari.com
Published in
7 min readMay 4, 2020
Photo by Alvaro Reyes on Unsplash

Functional Programming is one of the most important topics in JavaScript. In this article, I going to clear some of the cool things in functional programming like inner function, higher-order function, first-class function, callback function, closure, and implementing callback function, I will create some cool functions like (forEach(), map(), filter(), find()) etc. So, Let’s dive into it.

What is a Function?

Function is like a machine, which reduces our repeated task in our daily programming. It has three parts like input, processing, and output. In input, we will provide our data or value. In processing, that machine will process or manipulate our input data. After completing processing, when we call it, It will return a cool output for what it’s created.

What is Functional Programming?

Functional Programming is a newer paradigm than OOP which has made the life of a programmer easier to organize and manage his code. By using that, We can easily maintain DRY(Don’t Repeat Yourself) principle in our code. Thinking every solution of a single coding problem like a function is the main concept of functional programming.

Three Main Terms of Functional Programming:
1. Pure Function
2. First Class Function
3. Higher-Order Function

1. Pure Function

When a function returns the same output if you provide the same arguments and doesn’t have any side effect (doesn’t have any effect in outer code), it’s called pure function.

var name = "Justin Clark";
function sayHello(name) {
return 'Hello, ' + name;
}
// same output when provided same arguments.
console.log(sayHello("Jhon Doe"));
// expected output: Hello, Jhon Doe
console.log(sayHello("Jhon Doe"));
// expected output: Hello, Jhon Doe
// nothing change in name varieble which is outer of that function.
console.log(name); // expected output: Justin Clark

// Impure Function
function printPerson(person) {
person.name= 'Mr. Foo';
person.age = 40;
return person;
}
// Before function invocation
var person = { name: 'John Doe', age: 32 }
console.log(person);
// invoking the Function
console.log(printPerson(person));
// expected output: Hello, Jhon Doe { name: 'Mr. Foo', age: 40 }
// // After function invocation
console.log(person);
// expected output: Hello, Jhon Doe { name: 'Mr. Foo', age: 40 }
// After invoking the function person object is changed by printPerson function. That's why it's not a pure function.

2. First Class Function

When a function can be stored in variable, object, array, a function can be created wherever you want, a function can be passed as an argument of another function, can be returned from another function, that’s called First Class Function.

The features of First Class Function:
1. can be stored in variable, object and array.
2. can be created wherever you want.
3. can be passed as an argument of another function.
4. can be returned from another function.

// our function
function multifly(a, b) {
return a * b;
}
// can be stored in variable, object and array (Feature No: 1)
// stored in a varieble
var mul = multifly;
console.log(mul(5, 2));
// expected output: 10
// stored in an array
var arr = [ multifly ]
console.log(arr[0](5, 2));
// expected output: 10
// stored in an object
var obj = { numOne: 5, numTwo: 5, multifly }
console.log(obj.multifly(5, 5));
// can be created wherever you want (Feature No: 2)
// created in an Object
const personData = {
firstName : "John",
lastName : "Doe",
getFullName : function () {
return this.firstName + ' ' + this.lastName;
}
}
console.log(personData.getFullName());
// expected output: John Doe
// created in an Array
const namesArr = [
'Justin',
'Clark',
function fullName() {
return namesArr[0] + ' ' + namesArr[1];
}
];
console.log(namesArr[2]());
// expected output: Justin Clark
// can be passed as an argument of another function(Feature No: 3)
// anonymous function passed as an argument of setTimeout() function.
setTimeout(function() {
console.log("Hello World");
}, 3000)
// can be returned from another function (Feature No: 3)
function printNum () {
var num = 2;
return function () {
return num;
}
}
console.log(printNum()());

3. Higher-Order Function

When a function can take one or one more function as his argument or can return another function as his result, that’s called a higher-order function.

function sum(a, b) {
return a + b;
}
function getMultifliedNumber (a, b, func) {
var sub = a - b;
return function (){
var sum = func(a, b);
return sum * sub;
}
// returned a function
}
var multifliedNumber = getMultifliedNumber(5, 3, sum);
// sum function is passed as an argument/
console.log(multifliedNumber());
// expected output: 16

Inner Function

When a function is declared inside another function, that’s called inner function.

Image of Inner Function

Closure

If a scope can access the data which is coming from his parent scope, we can call that closure.

Image of closure
Output of closure

Callback Function

Callback function is one of the most popular and coolest terms in JavaScript. When a function is passed as an argument of another function for doing a specific task what we want to do, that’s called a callback function.

function calculate(a, b, callbackFunc) {
var sum = a + b; // 8
var sub = a - b; // 2
var result = callbackFunc(sum, sub);
return result;
}
const addition = calculate(5, 3, function (a, b) {
return a + b;
});
console.log(addition);
// expected output: 10
const subtraction = calculate(5, 3, function (numOne, numTwo) {
return numOne - numTwo;
});
console.log(subtraction);
// expected output: 6
const multiplication = calculate(5, 3, function (numOne, numTwo) {
return numOne * numTwo;
});
console.log(multiplication);
// expected output: 16
const division = calculate(5, 3, function (numOne, numTwo) {
return numOne / numTwo;
});
console.log(division);
// expected output: 4

Implementing Callback Function

In this section, I am going to create some cool function like forEach(), map(), find(), filter(), findIndex() etc by implementing Callback Function.

Implementation of forEach()

const arr = [2, 3, 5, 6, 7, 9, 10]function ourForEach(array, callbackfn) {
for (let i = 0; i < array.length; i++) {
const value = array[i];
callbackfn(value, i, array);
}
}
ourForEach(arr, function (value, index, array) {
console.log(value, index, array);
});
/*
expected output:
2 0 [2, 3, 5, 6, 7, 9, 10]
3 1 [2, 3, 5, 6, 7, 9, 10]
5 2 [2, 3, 5, 6, 7, 9, 10]
6 3 [2, 3, 5, 6, 7, 9, 10]
7 4 [2, 3, 5, 6, 7, 9, 10]
9 5 [2, 3, 5, 6, 7, 9, 10]
10 6 [2, 3, 5, 6, 7, 9, 10]
*/

Implementation of map()

const arr = [2, 5, 6, 7, 9, 8]function ourMap(array, callbackfn) {
const newArr = [];
for (let i = 0; i < array.length; i++) {
const element = callbackfn(array[i], i, array);
newArr.push(element);
}
return newArr;
}
const doubleIt = ourMap(arr, function(value) {
return value * 2;
})
console.log(doubleIt);
// expected output: [ 4, 10, 12, 14, 18, 16 ]
// square every element using arrow function and ourMap function
const squareIt = ourMap(arr, value => value * value);
console.log(squareIt);
// expected output: [ 4, 25, 36, 49, 81, 64 ]

Implementation of reduce()

const arr = [2, 5, 6, 7, 9, 8]function ourReduce(array, callbackfn, accumulator) {
for (let i = 0; i < array.length; i++) {
const element = array[i];
accumulator = callbackfn(accumulator, element)
}
return accumulator;
}
const total = ourReduce(arr, function(initialValue, value) {
return initialValue + value;
}, 0);
console.log(total);
// expected output: 37

Implementation of find()

const arr = [2, 5, 6, 7, 9, 8]function ourFind(array, callbackfn) {
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (callbackfn(element)) {
return element;
}
}
}
const findValue = ourFind(arr, function (value) {
return value > 5
});
console.log(findValue);
// expected output: 6

Implementation of findIndex()

const arr = [2, 5, 6, 7, 9, 8]function ourFindIndex(array, callbackfn) {
for (let i = 0; i < array.length; i++) {
if (callbackfn(array[i])) {
return i;
}
}
}
const findIndex = ourFindIndex(arr, function (value) {
return value > 5
});
console.log(findIndex);
// expected output: 2

That’s all for now. I have discussed here about the core concept of functional programming. I think it will help to improve your coding skills, coding quality which is most important to be a cool programmer. If you have any comments or suggestions, feel free to drop it below.

--

--