×

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

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 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 Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 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.

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.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

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 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 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 Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

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.

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.

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.