“Higher-order function” is a term we often come across, called “higher-order function” in English, which is quite mysterious to beginners. Today, we’re going to talk about higher-order functions.

define

A function that takes a function as an argument or returns a function

In plain English:

  1. First of all it’s a function
  2. Arguments or return values are functions

For example,

Here we take two examples to override the above definition. Example 1 is a higher-order function that receives a function as an argument, and Example 2 is a higher-order function that returns a function.

Example 1: Function as argument

We defined a function called evaluatesToFive that takes two arguments: the first argument is a number and the second argument is a function. In evaluatesToFive, pass argument one (number) to argument two (function)

function evaluatesToFive(num, fn) {
  return fn(num) === 5;
}
Copy the code

Scenarios used:

function divideByTwo(num) {
  return num / 2;
}

evaluatesToFive(10, divideByTwo);
// true

evaluatesToFive(20, divideByTwo);
// false
Copy the code

Ha ha, although functions themselves are not very useful, they are easy to understand for describing higher-order functions.

Example 2: Return a function

In this case, we create a function multiplyBy, which takes a number as an argument and returns a new function

function multiplyBy(num1) {
  return function(num2) {
    return num1 * num2;
  };
}
Copy the code

Usage Scenarios:

const multiplyByThree = multiplyBy(3); const multiplyByFive = multiplyBy(5); multipyByThree(10); // 30 multiplyByFive(10); / / 50Copy the code

If you feel a little bit, generate new functions for a more specific purpose.

More complex application examples

In this example, we create a function to check if the new user’s registration information passes the validation rule:

  • More than 18 years of age
  • The password must contain more than 8 characters
  • Agree user agreement

A new user’s registration information would look something like this:

const newUser = {
  age: 24,
  password: 'some long password',
  agreeToTerms: true};Copy the code

Next, we create three validation functions that return true and false otherwise

function oldEnough(user) {
  return user.age >= 18;
}

function passwordLongEnough(user) {
  return user.password.length >= 8;
}

function agreeToTerms(user) {
  return user.agreeToTerms === true;
}
Copy the code

Next, the hero comes in, and we need to create a higher-order function to do all the validation at once. The first parameter is the new user registration information, and the remaining parameters are the three validation functions we created above. Perform the validation in sequence in the function body:

functionvalidate(obj, ... tests) {for (let i = 0; i < tests.length; i++) {
    if (tests[i](obj) === false) {
      return false; }}return true;
}
Copy the code

Use:

const newUser1 = {
  age: 40,
  password: 'tncy4ty49r2mrx',
  agreeToTerms: true}; validate(newUser1, oldEnough, passwordLongEnough, agreeToTerms); //true

const newUser2 = {
  age: 40,
  password: 'short',
  agreeToTerms: true}; validate(newUser2, oldEnough, passwordLongEnough, agreeToTerms); //false
Copy the code

So far, so good. Keep going. How can we improve

Continue to evolve

In the previous section, we used validate to pass in multiple validation functions (oldEnough, passwordLongEnough, agreeToTerms), which violates the least knowledge principle (for those of you who are interested). Let’s see how we can continue to improve:

functioncreateValidator(... tests) {return function(obj) {
    for (let i = 0; i < tests.length; i++) {
      if (tests[i](obj) === false) {
        return false; }}return true;
  };
}
Copy the code

The createValidator function is awesome. It takes any number of functions as arguments and returns a function. So the createValidator is also a higher-order function.

Use:

const userValidator = createValidator(
  oldEnough,
  passwordLongEnough,
  agreeToTerms
);

userValidator(newUser1); // true
userValidator(newUser2); // false

Copy the code

You see where this is going? The createValidator function generates a more specific validation function, userValidator, which is then used to validate the registration information of the new user. What a wonderful higher-order function! For those of you who haven’t had enough, there’s another term that you can use!

conclusion

In this article, we discussed the JS higher-order function, do not think that higher-order function is only an interview question. Higher-order components that are popular in front-end frameworks also reference higher-order functions. High-order functions are often used in our daily development. With good use, many complex business logic can be decoupled, which makes sense for the readability and maintainability of the code! Closure knowledge is also used in the article. Did you find it clever? Don’t let your knowledge lie in the interview questions forever!