×

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

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.

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 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 Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute 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 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 Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

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

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 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 input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

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.