Functional Programming in JavaScript
Posted by Superadmin on May 02 2023 13:20:23

Functional Programming in JavaScript

By Payal UdhaniPayal Udhani
  

functional programming in javascript

What is Functional Programming in Javascript?

Functional Programming is a programming pattern or practice based on pure functions that focus on avoiding data sharing and mutations. Javascript is a multi-paradigm language that can be used as procedural, object-oriented, and functional according to our necessities and implementation. The most important feature was the first-class usage which was not used in java until version 8. Functional Programming was possible in Javascript just because of the first-class usage. It made the code more readable and boost the execution. Examples of functional programming boosting the execution performance are angular and react. The procedural loops can be replaced with functions that make coding, reading, and debugging more easier.

It is very necessary to understand what are all the functions or coding styles in which functional programming does not include in its code. So firstly we will learn about all the coding parameters not used in functional programming.

So we aim to write a code that will not use the above-mentioned things to write a functional program in javascript.

Pure Functions & Impure Functions

Even if your code contains multiple functions in it, it cannot be called a functional program. Those functions must be pure functions that mean at any given state it should return the same output for the same inputs and should not vary. This is called referential transparency and it should not depend on any mutable state. This is the first condition that a pure function must follow, the second one is that it should have no side effects. It consists of muting any object or assigning value to the variables again or any of the IO operations like logging or writing to console.

Code:

<!DOCTYPE html>
<html>
<body>
<p>Demonstration of a functional program:</p>
<button type="button" onclick="myFunction()">Click here to get results!</button>
<p id="sampleDemo"></p>
<script>
function myFunction() { var a = 4;
var b = 9;
document.getElementById("sampleDemo").innerHTML = add(a,b);
}
function add(int1, int2) { return int1 + int2;
}
</script>
</body>
</html>

Output:

Functional Programming Output 1

After clicking on the button,

Output:

Functional Programming Output 2

Note that here, myFunction is not a functional code while add function is a functional method as it returns the same results for the same inputs and has no side effect. We have a focus on how we can convert our whole program into a functional program. In reality, it is not possible because we often require runtime side effects to be generated in some situations. Here, we can make an 80-20 rule. Where you try to make 80% of your code functional while the remaining 20% can be non-functional along with its output statements and IO side effects.

How Can We Achieve Functional Programming Completely?

Here, we have to make sure that there’s immutability in variables that can be achieved by using const instead of let or var for declaring object references. As const stands for constants, its reference value can never be changed. Second thing is that we have to make sure about the value of the objects is not modified at all which can be achieved by using Object. Freeze method in javascript.

Object.freeze method can be used when we don’t want the value of the object to be manipulated or changed ever.

Example #1

Let us check how functional programming can be achieved while using normal variables and objects with the help of an example.

Code:

<!DOCTYPE html>
<html>
<body>
<p>Demonstration of a functional program:</p>
<button type="button" onclick="myFunction()">Click here to get results!</button>
<p id="sampleDemoObject1"></p>
<p id="sampleDemoObject2"></p>
<p id="sampleDemoObject3"></p>
<p id="sampleDemoObject4"></p>
<script>
function myFunction() {
// CASE first: In first case, we will keep object as mutable and its variable can also be reassigned
let object1 = { sampleStatement: 'object1 sample statement value' };
// Object can be mutated
object1.sampleStatement = 'object1 sample statement modified value';
// variables can be reassigned
object1 = { message: "new object of object1 reference with sample statement value" };
// CASE second: In second case, we will keep object as mutable but its variable cannot be reassigned
const object2 = { sampleStatement: 'object2 sample statement value' };
// Object can still be mutated
object2.sampleStatement = 'object2 sample statement modified value';
// variables cannot be reassigned
// object2 = { message: 'new object of object2 reference with sample statement value' }; // result into an error!
// CASE third: In third case, we will keep object as immutable but its variable can be reassigned
let object3 = Object.freeze({ sampleStatement: "object3 sample statement immutable value" });
// Object cannot be mutated
// object3.sampleStatement = 'object3 sample statement modified value';
// result into an error!
// variables can be still reassigned
object3 = { message: "new object of object3 reference with sample statement value which can be modified" };
// CASE forth: In forth case, we will keep object as immutable but its variable
//cannot be reassigned which helps us in achieving the functional programming
const object4 = Object.freeze({ sampleStatement: 'object4 sample statement immutable value which can never be changed' });
// Object cannot be mutated
// object4.sampleStatement = 'object4 sample statement modified value' // result into an error!
// variables cannot be reassigned
// object4 = { message: "object4 sample statement modified value with modified reference" }; // result into an error!
document.getElementById("sampleDemoObject1").innerHTML = object1.sampleStatement ;
document.getElementById("sampleDemoObject2").innerHTML = object2.sampleStatement ;
document.getElementById("sampleDemoObject3").innerHTML = object3.sampleStatement ;
document.getElementById("sampleDemoObject4").innerHTML = object4.sampleStatement ;
}
function add(int1, int2) { return int1 + int2;
}
</script>
</body>
</html>

Output:

Sample Statement Example 1

It is also necessary to avoid using push(), pop() and other methods described above. Instead, they can be modified into functional programming in the following manner.

Example #2

Code:

<!DOCTYPE html>
<html>
<body>
<p>Demonstration of a functional program in arrays:</p>
<button type="button" onclick="myFunction()">Click here to get results!</button>
<p id="sampleArrayObject1"></p>
<p id="sampleArrayObject2"></p>
<p id="sampleArrayObject3"></p>
<script>
function myFunction() {
const array1 = Object.freeze([10, 11, 12]);
// Instead of: array1.push(13, 14, 15);
const array2 = array1.concat(13, 14, 15);
// Instead of: array1.pop();
const array3 = array1.slice(0, -1);
document.getElementById("sampleArrayObject1").innerHTML = array1 ; document.getElementById("sampleArrayObject2").innerHTML = array2 ; document.getElementById("sampleArrayObject3").innerHTML = array3 ;
}
</script>
</body>
</html>

Output:

Array Example 2

Similarly, we can achieve this for sets and maps. Functional programming boost ups the performance and hence should be maximumly inculcated in your program.