HIGHER-ORDER FUNCTIONS

Ashish Kumar
2 min readMar 15, 2020

--

https://www.google.com/url?sa=i&url=https%3A%2F%2Fblog.webf.zone%2Fpractical-functional-javascript-step-2-higher-order-functions-c1419d042417&psig=AOvVaw3JTYZAvomlWOuHnShOx1IY&ust=1584376644747000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKigt5j1nOgCFQAAAAAdAAAAABAD

A higher-order function is a function that takes a function as an argument or returns a function. The higher-order function makes your code easier to understand and maintain. It also makes it easy to combine functions with each other. for examples .filter(), .map() and .reduce().Thesefunctions take a function as an argument. These are higher-order functions.

Filter

This method creates a new array with all elements that pass the test implemented by the provided function.

const words = ['spray', 'limit', 'elite', 'exuberant',           'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result);// expected output: Array ["exuberant", "destruction", "present"]

Map

Let’s take the same list of people and an array of names that a person loves to watch movies. The map method creates a new array populated with the results of calling a provided function on every element in the calling array.

const movieLovers = [‘John Doe’, ‘Liam Smith’, ‘Jessy Pinkman’];const result = words.map(word => word.length > 6);console.log(result);

Reduce

This method used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Parameter: This method accepts two parameters.

  • Function(total, currentValue, index, arr): It is the required parameter and used to run for each element of the array. It contains four-parameter which are listed below:
  • Total: It is the required parameter and used to specify the initialValue or the previously returned value of the function.
  • CurrentValue: It is a required parameter and used to specify the value of the current element.
  • CurrentIndex: It is an optional parameter and used to specify the array index of the current element.
  • Arr: It is an optional parameter and used to specify the array object the current element belongs to.
  • Initial value: It is an optional parameter and used to specify the value to be passed to the function as the initial value.

--

--