What is a higher-order function

Functions that take arguments or return values as functions are called higher-order functions

Function as argument

Pass a function as an argument to another function

fucntion forEach(array,fn){ for(let i=0; i<array.length; i++){ fn(array[i]) } }Copy the code

Function as the return value

Treat a function as the return result of another function

function once(fn){ let done = false return function(){ if(! done){ done = true return fn.apply(this,arguments) } } }Copy the code

Common higher-order functions

// map const map = (array, fn) => { let results = [] for (let vlue of array) { result.push(fn(value)) } return result } // every const every = (array, fn) => { let result = true for (let value of array) { result = fn(value) if (! result) { break } } return result } // some const some = (array, fn) => { let result = false for (let value of array) { result = fn(value) if (result) { break } } return result } // filter const filter = (array, fn) => { let result = [] for (let i = 0; i < array.length; i++) { if (fn(array[i])) { results.push(array[i]) } } return result } // forEach const forEach (array, fn) => { for (let i = 0; i < array.length; i++) { fn(array[i]) } }Copy the code