1. What are higher-order functions

One of the two properties is a higher-order function

1) A function has one argument that is a function; Commonly used callback functions

const cb = () => console.log('cb')

function fn(callback) {
    callback && callback()}

fn(cb)
Copy the code

2) Function returns a function; Often used for closures

function fn() {
    return function () {}
}

fn()
Copy the code

2. What problems can higher-order functions solve

1) For example, we often use the decorator pattern (slice programming). Application: Log the application, decorate the original core code, do something before calling the core code, do something after.

function core() { // todo... It is our business code of the console. The log (' core execution ')} / / to the Function prototype plus before method Function. The prototype. Before = Function (beforeFn) {return (... args) => { beforeFn() this(... Const newFn = core.before(() => {console.log(' before core ')}) newFn() // before core call // core executionCopy the code

2) Coriolization of functions; Numerical summation examples, data type judgment

/ * * * * typeof judgment variable data type (can't distinguish between Object) * constructor (judgment constructor) * instanceof * Object. The prototype. ToString. Call * / / / the sum function Function sum(a, b, c, d) {return a + b + c + d} @param Array arr const curring = (fn, const curring) Arr = []) => {const len = fn. Length return function (... args) { const newArr = [...arr, ...args] if (newArr.length === len) { return fn(... newArr) } else { return curring(fn, newArr) } } } const newSum = curring(sum) console.log(newSum(1)(2)(3)(4)); // 10 console.log(newSum(1, 2)(3)(4)); Function isType(type, val) { return Object.prototype.toString.call(val).toLowerCase() === `[object ${type}]`.toLowerCase()}const newIsType = curring(isType)const isString = newIsType('String')console.log(isString('22')); // trueCopy the code

3, summarize

There are many higher-order functions used in the actual development. In addition to the above two, there are callback functions, closures, promises, stabilization, throttling, and some iteration methods of arrays (forEach, map). This is a conceptual distinction.