×

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for object-oriented programming, at some point we may turn back while writing code for some tasks.

At this moment, functional programming comes up in our mind which helps us in writing efficient and more readable code that performs our tasks easily.

Functional programming involves writing functions that can be compounded or pure functions. These functions handle the sub-tasks to be performed while solving a complex problem.  

JavaScript provides an ecosystem for both object-oriented and functional programming. However, recently functional programming gaining more popularity in developing web applications using frameworks such as React and Angular.

It boosts performance with its core feature of immutability and also it makes debugging easier with writing pure functions. Using functions instead of procedural loops makes the program more readable and elegant.

There are two types of programming paradigms that help in achieving different outputs.

Declarative Programming:

It can be defined as a programming paradigm that specifies the compiler what to do or the logic behind the program. We use certain functions in the programs to get certain outputs.

Example:

<!DOCTYPE html>
<html>
  
<head>
    <script src=
"//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js">
    </script>
</head>
  
<body>
    <script>
        const myarr = [1, 2, "13", 
            "10", 5, 6, "11", 8, "9"];
  
        function even(n) {
            return n % 2 === 0;
        }
  
        const filteredevenArr = R.filter(
            even, R.map(Number, myarr));
  
        // [2, 4, 6, 8]
        console.log(filteredevenArr); 
    </script>
</body>
  
</html>

Output:

[2, 10, 6, 8]

Imperative Programming:

It can be defined as a programming paradigm that specifies the compiler

how to perform a task by describing the program’s control flow so we can get the desired output.

Example:

const list = [1, 2, 3, 4, 5];


const sumOfList = (n) => {


let finalResult = 0;
for (let i = 0; i < n.length; i++) {
  finalResult += n[i];
  }
return finalResult;
}
Const sum= sumOfList(list)
Console.log(sum)

Output:

15

We have seen both programming styles but functional programming is mostly associated with declarative type programming as it always resembles what to do to perform a given task.

 There are some concepts involved in functional programming while implementing JavaScript. By understanding them clearly, we can write more functional code and can implement them easily while solving a specific problem.

First-Class Objects

The first-class objects in JavaScript are the functions and we can use the functions in our JavaScript program just like variables.

These functions are the objects having properties and can call other functions.

Example:

const sum = (num1, num2) => num1 + num2;


const addition = sum(1, 2);


const additionAgain = (num1, num2, sum) => sum(num1, num2);

JavaScript allows us to work with functions in different ways like:

  • Functions can be assigned to a variable as a value.
  • Functions are provided as arguments to other functions.
  • Functions are used in different data types. 
  • They can be even obtained as a return value from other functions.

Pure Functions in JavaScript

Functions that take given input and always provide the same output are known as pure functions in JavaScript.

Functional programming makes us write pure functions which can be managed and tested easily. Pure functions do not involve making changes to another part of the code like object modifying, calling other functions, etc.

Let’s look at an example of a pure function:

const display = (name) => `Hello ${name}`;


display("Javatpoint") // It always return "Hello Javatpoint"

Pure functions are powerful and they can be debugged easily. We can also test this function easily as it returns the same output for a given specific input.

These simple functions are the building blocks that are independent and reusable while developing an application.

Higher-Order Functions in JavaScript

In functional programming, we can say that it is a powerful concept that is used to obtain better functionality in the program.

It is defined as a function that receives another function as an argument and provides a function as a return value. Some of the examples of higher-order functions are reduce map, and filter methods.

They are complex functions that are used to create functions, change other functions and work with different data types.

Let’s look at an example program implementing higher-order functions.

Example:

cont cars = [
	  { make: 'Tata', model: 'Harrier-xe', type: 'suv', price: 24045 },
	  { make: 'Honda', model: 'Accord', type: 'sedan', price: 22455 },
	  { make: 'Mazda', model: 'Mazda 6', type: 'sedan', price: 24195 },
	  { make: 'Mazda', model: 'CX-9', type: 'suv', price: 31520 },
	  { make: 'Toyota', model: '4Runner', type: 'suv', price: 34210 },
	  { make: 'Toyota', model: 'Sequoia', type: 'suv', price: 45560 },
	  { make: 'Toyota', model: 'Tacoma', type: 'truck', price: 24320 },
	  { make: 'Tata', model: 'Nexon', type: 'ev', price: 27110 },
	  { make: 'Ford', model: 'Fusion', type: 'sedan', price: 22120 },
	  { make: 'Ford', model: 'Explorer', type: 'suv', price: 31660 }
	];  //array of objects
	


	const averageSUVcarPrice = cars
	  .filter(v => v.type === 'suv')
	  .map(v => v.price)
	  .reduce((sum, price, i, array) => sum + price / array.length, 0); //higher order function calculating average price of suv
	


	console.log(averageSUVcarPrice);
const averageSUVPrice1     = R.pipe(
	R.filter(v => v.type === 'suv'),
	  R.map(v => v.price),
	  R.mean
	)(cars); // using pipe which runs the function  from top
console.log(averageSUVcarPrice);

Output:

33399
33399

In the above example, we can observe that we passed an array of objects to the called methods and we calculated the average car price based on the type.

We also used the pipe which gave us the same output.

Composition in JavaScript

In functional programming, sometimes it is very important to know how to combine multiple functions to produce a new function that computes the given task.

Composition is defined as the process of bringing multiple functions together and making another new function that solves our problem quickly.

It involves passing parameters or input data from right to left and providing the output obtained from one function to another left side function as an input. Through understanding of this concept makes you create a better composition function that is more readable and performs the given task.

Look at the given example program of composition in JavaScript.

const splitName = (myname) => myname.split('_').join(' ');


const returnNameCapitalized = (myname) => myname.toUpperCase();


console.log(returnNameCapitalized(splitName('jennifer_lopez')));

Output:

Jennifer Lopez

Immutability in JavaScript

We can understand the concept by the name itself immutable which means cannot be further modified. Once the object is created, we cannot change it that is called an immutable object.

What if we need to change the immutable object?

The answer that we can say to the above question is we can only create a copy of the actual object and we should make changes to it as we cannot mutate the actual object.

There is no guarantee in JavaScript functional programming that we can achieve immutability accurately. We should not use some array methods such as push, sort, fill, unshift, pop, reverse, etc to maintain immutable data in your application.

We can also make use of Object.assign, a method to achieve the immutability property of an object.

The method Object.assign is an ES6 feature that is used to assign new properties to an immutable object.

Example:

const mycar = {
  model: 'Tata',
  year: 2020
  }
const newcar = Object.assign({}, mycar, {
  model: ‘Honda’
  })

Here, using the Object.assign method we created another object newcar, and assigned new property along with the old properties of the actual object.

Uses of Functional Programming

There are many benefits to using functional programming which made it more popular and trending while working on frontend applications especially React and Vue frameworks.

Let’s discuss some of them.

No side Effects and Immutable

The most important benefit of using functional programming is its ability to eliminate side effects in the code. It also reduces the bugs, which occur while we try to change some global objects or variables, and also it is easy to find them as the scope of occurrence is only within the function.

Functional Programming deals with writing pure functions, where they care about the things happening within their scope and return output according to the given input. Thus, there will be a low possibility of happening unexpected errors.

Clean and Straightforward

As Functional Programming is always straightforward, it is easy to identify some bugs and unexpected errors in the functions. The creation of functions and maintaining them is easy than dealing with classes in object-oriented programming. We also know about the KISS principle while developing and designing applications, which is strictly followed by Functional programming.


Related Topics

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.