Functional Programming

A paradigm that treats computation as the evaluation of mathematical functions on Iterable objects is called Functional Programming. A set of certain statement is defined to perform the same operation on any data type for which user has defined.

We use forEach, map, filter, reduce, every and sort for functional programming.

Let's try to understand each method with multiple examples.

  • forEach(): This method is used when we want to perform any operation for each of the elements in array without skipping anyone and creating a new array as it does not return a new array.

    Assume it like you have five bank accounts having different amount , if you wish to increase the amount by Rs. 500 in all those five accounts then a function will be written which will be applied for each of the accounts, no matters what's the initial amount.

**Suntax:**arrayName.forEach(function(value, index, array), thisValue)

Looking at the parameters.

ParameterPurpose
functionIt's must to either pass a function or define a function which will be performed on each element.
valueIt holds the value of the element passed currently.
indexIt's user's choice to pass the initial index of the element or leave as it is.
arrayIt's also user's choice to pass the array for that element.
thisValueIt's also user's choice, needed when callback is used to pass certain value as parameter.

Example 1: Print all the elements of array usingforEach.

Approach a-

//Using arrow function
let array=[1,2,3,4,5];
array.forEach((element)=>{
    console.log(element);
})

Output:1 2 3 4 5

Approach b-

//Using name function
let array=[1,2,3,4,5];
array.forEach(function print(element){
    console.log(element);
})

Output:1 2 3 4 5

Approach c-

//Defining a function outside
let array=[1,2,3,4,5];
function print(element){
    console.log(element);
}
array.forEach(print);

Output:1 2 3 4 5

So we saw that there are multiple approach to print the elements and which depends on user.

Example 2: Calculate the square of each element in the array.

//I've used arrow function approach
let array=[5,4,3,2,1];
array.forEach((element)=>{
    element*=element;
    console.log(element);
})

Output: 25 16 9 4 1

Example 3: Multiply each element of array and pass item, index and array in the parameter.(Passing parameter is optional by default)

let array=[5,4,3,2,1];
array.forEach((element,index,array)=>{
    array[index]*=10;
    console.log(array[index]);
})

Output: 50 40 30 20 10

Try to understand that what's happening here. Earlier we used to pass only one parameter that's each element but here index and array is also passed. By default index value is 0, element is that 1st element i.e 5 and array is same in each case. Now this continues till last element. Hence output is 50 40 30 20 10.

Note: In all the examples we have directly changed the original array. In each case if we try to access the array again we'd get the computed value by the function for each element.

  • map(): This method is used when we want to return a new array by applying a function to each element of the original array. The length of new array is same as that of array on which map method is applied.

    Assume it like you are a bank manager handling thousands of customers transaction. Take two cases ; number one you want to greet the account holders and update them about policy so here you'll useforEachmethod but in case you want to generate a list of customers who had taken loan and show there loan amount so here you'll usemapmethod to create a new file for the same . With this you must have analyzed than in 1st case you need not to create any new file but in 2nd case you'll have to create

Syntax is same as forEach i.e

arrayName.forEach(function(value, index, array), thisValue) {Parameters are also same}

Example 1: There is a website of grocery store on which some products are listed, once a user adds that product in the cart the original price is stored in the array namedproductPrice. The developer forgot to add Rs. 2 extra on each product as said by owner so you're asked to work on backend part to return the modified price for final evaluation. Let a user has selected 5 items now modify it as per owner's need.

let  productPrice=[23,45,65,12,76,10];
let finalPrice=productPrice.map((element)=>{return element+=2});
console.log(finalPrice);

Output: [25 47 67 14 78 12]

Point to be noted here that while using map method return keyword is used which is returning the modified element in each case.

Example 2: You have to make a temperature converter website from Celsius(°C) to Fahrenheit(°F) but the API which you are using is giving you the temperature in Celsius. You want to show both (°C) and (°F) temperature on your website. Handle this by taking last 5 days temperature.

let  celsiusTemp=[20,32,27,18,10];
let fahrenTemp=celsiusTemp.map((temp,index,celsiusTemp)=>{return (temp * 9/5) + 32;});
console.log(fahrenTemp);

Output: [ 68, 89.6, 80.6, 64.4, 50 ]

As earlier mentioned that the syntax for forEach and map is same the difference is map returns a new array. Same thing is happening here in parameter temp, index and array(celsiusTemp) is passed.

Example 3: You have made a feedback form in which a user needs to fill first name and last name. Till now you're receiving the details filled by user on your email properly. Suppose you want to send back a confirmation mail to user what he/she has filled has been successfully received. Suppose the first name and last name is being stored in array, write a suitable code for 5 customers.

let nameArray=[
        {Firstname: "Ritik",
         Lastname: "Raushan"},
         {Firstname: "Anamika",
         Lastname: "Vats"},
         {Firstname: "Neha",
         Lastname: "Rani"},
         {Firstname: "Sachin",
         Lastname: "Saurav"},
         {Firstname: "Mangal",
         Lastname: "Pandey"},
    ]

let fullName=nameArray.map((element)=>{
    return element=element.Firstname+" "+element.Lastname;
})
console.log(fullName);

Observing carefully to the code and output; nameArray is an array of object which stores First name and Last name. Later using map method I'm trying to concatenate the first name and last name which is stored in an array fullName .So in this way you can now send back the confirmation mail accessing the element of this new array.

  • filter(): This method is used when we want if the particular element satisfies my condition then return me in a new array with all satisfying elements. It's commonly used to extract elements from an array based on a condition.

    Assume it like you are class monitor and your class teacher asked you to call all the students who have scored more than 95% in last examination. You went to class and asked everyone for his/her marks. Now you're having a collection of students marks. You then will apply the condition than one having more than 95% will go along with you . So basically you filtered the marks on the applied condition.

    Syntax is same as of that forEach and map.

    Let's try to visualize it with some problems.

    Example 1: You are working in your Block as a clerk handling fund transfer. The BDO has asked you that there's a scheme that the person whose age is more than 60 years will get pension through DBT(Direct Benefit Transfer). From the government website you can access that how many applicants have sent request. Let an array of object havingage, aadhar and balanceis given

    now you have to send Rs. 400 on each eligible aadhar and show the balance top BDO.

  •       let ageAadhar=[
                  {age:60,
                  aadhar: "12345",
                  balance: 1000},
                  {age:55,
                  aadhar: "12346",
                  balance: 500},
                  {age:66,
                  aadhar: "12347",
                  balance: 1100},
                  {age:48,
                  adhar: "12348",
                  balance: 700},
                  {age:75,
                  aadhar: "12349",
                  balance: 2700},
    
              ]
    
          let eligible=ageAadhar.filter((element)=>{
              return element.age>=60;
          });
    
          console.log(eligible);
    
          eligible.forEach((element)=>{
              element.balance+=400;
          })
    
          console.log(eligible);
    

    Output:

  • In the above code ageAadhar is an array of objects which holds age, aadhar and balance. Now since my problem statement was to send Rs. 400 on each eligible aadhar so I've first filtered the eligible age using filter method and then using forEach method transferred Rs. 400.

    From this example both forEach and filter method is revised.

We'll see in detail about reduce, every and sort in next article More on Functional Programming. Till then revise forEach , map and filter as much as possible.