Updated July 1, 2023
What is Functional Programming in Javascript?
Functional Programming is a programming pattern or practice based on pure functions that avoid data sharing and mutations. According to our necessities and implementation, we can use JavaScript as a multi-paradigm language that supports procedural, object-oriented, and functional programming. The most important feature was 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 boosted the execution. Examples of available programming boosting the execution performance are angular and react. Functions can replace procedural loops, making coding, reading, and debugging easier.
It is essential to understand all the functions or coding styles that functional programming does not include in its code. So firstly, we will learn about all the coding parameters not used in functional programming.
- All kinds of loops, including for, for each, while, do-while.
- Mutable Objects whose value of reference or content.
- Void functions that do not write anything as it is a possibility that they might be generating some side.
- Variables that are declared using let or.
- Array, Map, Or Set mutator functions like pop, push, copy, fill, reverse, shift, unshift, sort, splice, add, delete, clear, and set.
So we aim to write a code that will not use the abovementioned things to write a functional program in javascript.
Pure Functions & Impure Functions
Even if your code contains multiple functions, it cannot be called a functional program. Those functions must be pure functions that, mean at any given state, should return the same output for the same inputs and 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, assigning value to the variables, or any IO operations like logging or writing to the 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:
After clicking on the button,
Output:
MyFunction is not a functional code here, while add function is a functional method as it returns the same results for the same inputs and has no side effects. We focus on how we can convert our whole program into a functional one. In reality, it is impossible because we often require generating runtime side effects 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 variables’ immutability 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. We can ensure that the objects’ value is not modified at all by using Object.Freeze method in javascript.
When we don’t want the object’s value to be manipulated or changed, we can use the Object.freeze method.
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:
It is also necessary to avoid using push(), pop(), and other methods described above. You can modify them 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:
Similarly, we can achieve this for sets and maps. Functional programming boosts performance and should be maximumly inculcated in your program.
Recommended Articles
We hope that this EDUCBA information on “Functional Programming in JavaScript” was beneficial to you. You can view EDUCBA’s recommended articles for more information.