The introduction of

We all know that a function is a block of code designed to perform a specific task, to be executed when some code calls it, to get a return value, or to do something else. Functions have function names and arguments, and function arguments are the real values received when the function is called.

Higher-order function is a function of Higher order.

define

A function that satisfies at least one of the following conditions

  • Take one or more functions as input
  • Output a function

How do you make sense of this thing? As I mentioned in the introduction, functions actually refer to some variable. Since a variable can be a directional function, and the parameters of a function can receive variables, a function can receive another function as an argument, which is called a higher-order function

// A simple higher-order functionfunction add(x,y,f){
    returnf(x)+f(y); } var x = add (5, 6, and Math. The abs); / / - > 11Copy the code

Some common higher-order functions

Map, array.prototype. filter, and array.prototype. reduce. They take a function as an argument and apply that function to each element in the list.

Array.prototype.map

The map() method creates a new array. The result is the result returned by each element in the array calling a provided function, leaving the original array unchanged.

For example, we have a function f(x)=x2, and we want to apply this function to an array [1, 2, 3, 4, 5, 6, 7, 8, 9].

fuction pow(x){
    return x*x;
}
var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9];
var result=arr.map(pow);    //[1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
Copy the code

One thing to note: Map () takes pow, a function object itself.

Although the functions mentioned above can be realized by loops without higher-order functions, as a higher-order function, it can calculate arbitrarily complex functions, which also reflects the value of higher-order functions.

Array.prototype.reduce

The reduce() method performs a provided Reducer function (ascending execution) on each element in the array, summarizing its results into a single return value.

Array reduce() applies a function to Array [x1, x2, x3…]. The function must take two arguments, reduce(), and continue the cumulative calculation with the next element of the sequence, resulting in:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
Copy the code

For example, summing an Array can be implemented using reduce:

Var arr =,3,5,7,9 [1]; arr.reduce(function(x,y){
    returnx+y; }); / / - > 25Copy the code

Array.prototype.filter

The filter() method creates a new array that contains all the elements of the test implemented by providing the function, leaving the original array unchanged.

Filter is also a common operation to filter out some elements of an Array and return the rest. Like map(), filter() of Array receives a function. Unlike map(), filter() applies the passed function to each element in turn, and then decides whether to keep or discard the element depending on whether the value returned is true or false.

For example, in an Array, remove even numbers and keep only odd numbers:

Var arr =,2,3,4,5,6,7,8 [1]; var r=arr.filter(function(x){
   return(x%2 ! = = 0); }); console.log(r); / / = > hc-positie [1]Copy the code

To remove empty characters from an Array:

var arr = ['A'.' '.'B', null, undefined, 'C'.' '];
var r = arr.filter(function (s) {
    returns && s.trim(); // Note: Versions below IE9 do not have the trim() method}); r; / / /'A'.'B'.'C']
Copy the code

So! Filter () is actually a filter function.

The callback function

The callback received by filter() can take many arguments. Usually we just use the first parameter, which represents an element of the Array. The callback can also take two additional arguments that represent the position of the element and the array itself:

This is cleverly de-weighted using the filter (which I think is cool)

var arr = ['A'.'B'.'C'];
var r = arr.filter(function(element, index, self) { console.log(element); // Print in sequence'A'.'B'.'C'console.log(index); // Print 0, 1, 2 console.log(self); // self is the variable arrreturn true;
});

var r,arr=['apple'.'strawberry'.'banana'.'pear'.'apple'.'orange'.'orange'.'strawberry'];
r=arr.filter(function(element,index,self){
    return self.indexOf(element)===index;
});
Copy the code

In addition to the usual higher-order functions mentioned above, there are a number of more powerful higher-order functions, including sort(),every(),finf(),findIndex(),forEach(), etc., which I’ll refer to in the references below.

Function is output as the return value

Returns a function, as the name implies.

We can use the Object. The prototype. ToString. Call to get the corresponding Object returned string, to determine the type

let isType = type => obj => {
  return Object.prototype.toString.call( obj ) === '[object ' + type + '] ';
}

isType('String') ('123');		// true
isType('Array') ([1, 2, 3]). //true
isType('Number') (123); //true

Copy the code

conclusion

The function of higher-order function can be realized by ordinary function to a large extent, but higher-order function is more abstract and easy to understand the code, making the function more concise, when the function is complex, it can be very convenient to achieve the required function, which is a very good thing ~


Liao Xuefeng – higher order function; Wood – poplar front – order – higher – order functions