JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions

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.