Explain the concepts of functional programming in JavaScript


There are mainly two programming paradigms: The imperative programming paradigm and the declarative programming paradigm. Functional programming is a subtype of the declarative paradigm. The paradigm word refers to the approach to solving a particular problem.

Functional programming has been in use for the last decades but came in the trend after 2015 when the last main revised version of JavaScript was released. There are many benefits to using functional programming, which we will discuss in this tutorial.

Different Concepts of Functional Programming and their benefits

Functional programming works as mathematical function works. It allows developers to develop software based on function evaluation. It means programmers can break the code into small parts, which we can call the function, making it easy to evaluate and test code. The following concepts of functional programming are covered in this tutorial −

  • Pure Functions

  • Code Readability

  • Code maintainability and fewer bugs

  • Higher-order function

Pure Functions in JavaScript

Pure Functions

In JavaScript, we can write the pure function. In simple terms, a pure function takes the values as a parameter, performs some operations on that, and returns the output.

The pure function never shares any variable with other function or use a global variable.

The followings are the properties of a Pure function −

  • A pure function always returns the same output for a given input.

  • A pure function does not depend on any external state − A pure function does not depend on any external state or variables that are not passed to them as arguments.

  • A pure function does not produce any side effects − A pure function does not produce any side effects, such as modifying global variables or changing the state of external objects.

You can get a better idea about the pure function by the below example.

Example 1

In the example below, we have created the pure_func() named pure function, which takes the value as a parameter and multiplies it with 2. After that, it prints the value. Users can see that pure_func() is not sharing any variable globally with another function.

Also, we can use the global_var directly without passing it as a parameter of a pure function. Still, we have passed it as a parameter as a pure function never shares any variable declared outside the function's scope.

<html>
<body>
   <h2>Pure function in JavaScript</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let global_Var = 56;
      function pure_func(param) {
         param = param*2;
         output.innerHTML += "The Double value of param is " + param + " <br/>";
      }
      pure_func(global_Var);
      pure_func(30);
   </script>
</body>
</html>

Code Readability

As we write all logic with functions in functional programming, it makes our code more readable. For example, in other programming languages, iterate through the array we use for or while loop. But functional programming allows us to use the for-of loop, which makes code more readable and tells other developers that we wanted to iterate through the array and perform some operation on every array element.

Let’s look at another example. Suppose we want to filter some values from the array. In other programming approaches, we write a manual function to filter values, but in the functional programming approach, we can use the filter() method, demonstrating that we want to filter values from the array based on the particular logic.

Example 2

In the below example, we have used the filter() method to filter all divisible values by 10. Users can see how clear it looks, and it tells us that we want to filter something from the array.

Now, look at the naive approach to filter values. We use the for loop to iterate through the array and the if-statement to check for divisibility by 10 and push to another array. However, both codes will give the same result, but the first code is more readable.

<html>
<body>
   <h2>Using the <i> filter() </i> method to filter values from the array</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      // creating the array of values
      let array = [10, 20, 50, 54, 32, 60, 54];
      output.innerHTML += "Original Array: " + array + "<br>"; 
      // using the functional programming approach to filter 
      //all values which are divisible by 10
      let divisibleBy10 = array.filter((ele) => ele % 10 == 0);
      output.innerHTML += "All values divisible by 10: " + divisibleBy10;
      // using the normal approach to filter values
      let filterValues = [];
      for (let i = 0; i < array.length; i++) {
         let ele = array[i];
         if (ele % 10 == 0) {
            filterValues.push(ele);
         }
      }
   </script>
</body>
</html>

Code maintainability and fewer bugs

Functional programming allows us to make our code more maintainable. As we all know, code refactoring takes more time and cost than writing new code. Also, developers spend more time on code refactoring.

From the last example given above, we can understand that writing a second approach to filter values will take more time to understand fellow developers. So, if we perform every logic via function, it makes code more readable and maintainable.

Also, we can reduce the bugs by using functional programming. As we have seen in Example 1, When we use the functional approach, we don’t need to worry about the scopes and everything. If any beginner doesn’t have enough knowledge of the scope, they can write code full of bugs.

Furthermore, every part of the code has its scope, and we don’t need to use the `this` keyword to refer to the scope like in object-oriented programming language. So, not using this keyword can also reduce bugs.

Higher-order Function

The higher-order function allows us to pass the function as an argument of another function. For example, we can pass the callback function as an argument of the reduce() method of the array. In the callback function, we can write logic to reduce an array into a single element.

Example 3

In this example, we have used the reduce() method to reduce the array into a single element and passed the callback function as an argument. It represents the higher-order function as we have passed the function as an argument.

<html>
<body>
   <h2>Using the <i>reduce()</i> method to introduce higher order functions</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      // creating the array of values
      let array = [6, 7, 8, 42, 23, 43, 2, 43, 23, 3, 13];
      output.innerHTML = "Original Array: " + array + "<br>";
      // using the array.reduce() method to find the total of the array 
      //and pass the arrow function as an argument of the reduce() method
      let total = array.reduce((total, num) => {
         return total + num;
      });
      output.innerHTML += "The total of the array values: " + total;
   </script>
</body>
</html>

We have learned about the functional programming approach and how it is beneficial and different from the programming paradigm. We have learned that it provides a way to write maintainable and readable code with fewer bugs.

Updated on: 17-Jan-2023

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements