Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

JavaScript Functional Programming and its principle

JavaScript Functional Programming

JavaScript support multiple programming paradigms like object-oriented and functional paradigms. , most JavaScript libraries are multiple programming paradigms. However, JQuery has a strong flavor of functional programming, while Ext.js is a completely object-oriented JavaScript library. JavaScript was highly influenced by a variety of languages including

  1. An object-oriented language from Java,
  2. Functional language from Schema
  3. Prototype language

Javascript Functional programming

In Functional programming, functions are considered first-class citizens and this means we can do anything with a function that we do with an object. We can assign functions to a value as a reference, pass them as arguments in the function and return them as values.

JavaScript Functional Programming

Is Javascript functional programming ?.

Is Javascript functional programming ?. We can’t say yes or no, as Javascript support multiple programming paradigms as we had discussed earlier and even it is not purely functional programming. But Javascript supports many functional programming principles and is well suited to use for Functional programming.

There are different programming paradigms but two of the most popular paradigms are

  1. Object-Oriented Programming (OOP): Example javascript is pure OOP
  2. Functional programming: Example C language, is pure FP

Programming paradigms are based on several defining principles and are used to organize and characterize the design and construction of software applications. Functional Programming is a programming paradigm where programs are constructed by using pure function and avoiding concepts of shared state, and mutable data.

Characteristic of functional programming in Javascript

We can use javascript for functional programming, as in JQuery. These are the main features that allow us to use javascript as functional programming.

  1. Pure functions
  2. Declarative functions
  3. Higher-order functions
  4. Function composition
  5. Immutability
  6. Side effects
  7. Shared state

Javascript Pure function

The pure function is a computational analog of a mathematical function and function that adheres to the following rules.

  1. No side-effects: A pure function doesn’t change any values or data elsewhere in the program.
  2. The function return values are identical for identical arguments.
  3. The pure function should only depend on the value provided by its arguments.

The Javascript pure function makes code more predictable and easy to test. Here is an example of a Javascript pure function or Javascript functional programming example pure function.

function pureSquare(num) {
  return num;
}

console.log(pureAdd(10));
Output: 10

Higher-order function

A higher-order function is a function that takes another function as its argument or returns a function. We’ll learn some of the higher-order functions like map, filter, and reduce.

In this section, we will be learning the most important predefined function in JavaScript to perform an operation like (map, filter, reduce ) on a collection or an array.

Functional programming provides developers with the tools to abstract common collection operations into reusable, composable building blocks.  Most of the operations we perform on collections can be accomplished with five simple functions (some native to JavaScript and some included in the RxJS library):

  1. map
  2. filter
  3. concatAll
  4. reduce
  5. zip

Map: Javascript pure function example

the method creates a new array with the results of calling a provided function on every element in the calling or existing array. We have to supply an array, run that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case), and subsequently returns a new array once completed.

var numbers = [1, 4, 6, 10];
var doubles = numbers.map(function(x) {
   return x * 2;
});
// doubles is now [2, 8, 12, 20]
// numbers is still [1, 4, 6, 10]

//ES6 example

const numbers = [2, 14, 18, 22];
const halves = numbers.map(x => x / 2);
// halves is now [1, 7, 9, 11]
// numbers is still [2, 14, 18, 22]

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

In the second example, we are creating a new array containing only countries’ name from the existing array as follow.

var newArr = [
{ id: 1, country: "England" },
{ id: 2, country: "Scotland" },
{ id: 3, country: "Wales" },
{ id: 4, country: "Northern Ireland" },
{ id: 5, country: "Republic of Ireland" },
{ id: 6, country: "France" },
{ id: 7, country: "Germany" },
{ id: 8, country: "Italy" },
{ id: 9, country: "Spain" },
{ id: 10, country: "Belgium" },
{ id: 11, country: "Holland" },
{ id: 12, country: "Czech Republic" }
];
// New Array with only countries list
countries = newArr.map(x => return x.country);

console.dir(countries);

Filter:  Javascript Pure function example 2

The methodfilter() creates a new array with all elements that pass the test implemented by the provided function. Syntax of the filter function.

var newArray = arr.filter(callback[, thisArg])

When using the map method to create new arrays every value from the original array is mapped to the new array. As useful as this is there are times when you only want to retrieve specific values from an array. Using the filter method values can be retrieved if they meet specific criteria. Let’s take our previous example and use the filter method to only return every 4th item from the associative array:

var newArr = [
{ id: 1, country: "England" },
{ id: 2, country: "Scotland" },
{ id: 3, country: "Wales" },
{ id: 4, country: "Northern Ireland" },
{ id: 5, country: "Republic of Ireland" },
{ id: 6, country: "France" },
{ id: 7, country: "Germany" },
{ id: 8, country: "Italy" },
{ id: 9, country: "Spain" },
{ id: 10, country: "Belgium" },
{ id: 11, country: "Holland" },
{ id: 12, country: "Czech Republic" }
];
var countries = newArr.filter((x) => {
if(x.id % 4 === 0) {
    return x;
}
});
console.dir(countries);

// Outputs following to web console

[{id: 4, country: “Northern Ireland”},
{id: 8, country: “Italy”},
{id: 12, country: “Czech Republic”}]

Second example

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

let longWords = words.filter(word => word.length > 6);

// Filtered array longWords is ["exuberant", "destruction", "present"]

In the third example, we can also combine the filter and map methods for the above examples so we end up with an array populated solely with the names of every 4th company like so:

var existArr = [
{ id: 1, company: "EMC" },
{ id: 2, company: "Google" },
{ id: 3, company: "Facebook" },
{ id: 4, company: "Apple" },
{ id: 5, company: "Infosys" },
{ id: 6, company: "HLC" },
{ id: 7, company: "HP" },
{ id: 8, company: "Wipro" },
{ id: 9, company: "IBM" },
{ id: 10, company: "Paypal" },
{ id: 11, company: "Yahoo" },
{ id: 12, company: "Microsoft" }
],

companies = newArr.filter((x) => {
    if(x.id % 4 === 0){
        return x;
    }
    })
    .map(x => return x.company);
    console.dir(companies);
// Outputs following to web console

[“Apple”, “Wipro”, “Microsoft”]

Reduce():  Javascript pure function example

The reduce() method applies a function to an accumulator and each element in the array (from left to right) to reduce it to a single value.   Syntax reduces function.

 array.reduce((currentTotal, item) => { return item + currentTotal}, 0);
var totalSubtract = [175, 50, 25].reduce((currentTotal, item) => {
  console.log('a value:', currentTotal);
  return currentTotal - item;
}, 300);

Output 50 
Value of currentTotal for each iteration
1 iteration currentTotal value: 300
2 iteration currentTotal value: 125
3 iteration currentTotal value: 75

The reduce method accepts two parameters; first, the current total is the total of each iteration, the second item is each item in the array and its callback function for each iteration, and in the above example 300 is the initial value of the total.

The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue if supplied (see below).

Example one: simply reduce the function to calculate the sum of all the array elements.

// ES6 version
const total = [0, 2, 4, 6].reduce((sum, value) => sum + value, 10);
// total is 24


var flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => {
  console.log('a value;', a);
  return a.concat(b);
}, []);

As we have initial empty array and value of a for each iteration is 
a value; []
a value; (2) [0, 1]
a value; (4) [0, 1, 2, 3]
Wher all array element are concat to a and b will iteration 3 times 
b value; (2) [0, 1]
b value; (2) [2, 3]
b value; (2) [4, 5]

Related posts

JavaScript Functional Programming and its principle

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top