- All You Need to Know About higher-order Functions in JavaScript
- Original author: Rahul
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Zz Zhaojin
- Proofread by: Chzh9311, KimYangOfCat
A brief introduction to the development and use of JavaScript higher-order functions
As a JavaScript developer, you’ll often use higher-order functions, so it’s important that you understand them correctly. Currently, I see some developers often confused about the use of Reduce (). Therefore, this article will elaborate, and you should try to understand it step by step. I am sure you will master it.
Higher-order functions
In short, higher-order functions are those that take other functions as arguments or return other functions. Functions passed as arguments in higher-order functions are called callbacks.
Advantages of higher-order functions:
- They help us write clean code.
- Debugging is made easier by the simplicity of the code.
JavaScript now has some built-in higher-order functions that you might already be using without realizing it, such as filter(), reduce(), sort(), and forEach().
filter()
The filter method returns a new array of elements that pass a specific test provided by a callback function. Because filter requires a callback function, filter() is called a higher-order function.
The higher-order filter() callback argument is as follows:
- Element value (required)
- Index of the element (optional)
- Array object (optional)
let arr = [1.2.3.4.5];
const resultant Array = arr.filter((element ) = > {
return element > 3;
})
console.log(resultantArray); / / [4, 5]
Copy the code
In the example above, the elements in the ARR array are passed in turn to the filter() callback method to perform a specific test, element > 3. Those elements that pass the test are pushed to the resultantArray, which is why the output is [4,5], because 4 and 5 are the elements that pass the test.
The element argument gets the arR array’s element values in turn, first becoming 1 and then testing 1 > 3. If true, 1 is pushed to the result array, otherwise it jumps to the next element.
Example:
// Select persons under 18 years of age
const ageArray = [10.12.35.55.40.32.15];
const filterAgeArray = ageArray.filter((age) = > {
return age < 18; >});console.log(filterAgeArray);
/ / [10, 12, 15]
-----------------
// Filter positive numbers
const numArray = [-2.1.50.20, -47, -40];
const positiveArray = numArray.filter((num) = > {
return num > 0;
});
console.log(positiveArray);
/ / [1, 50, 20]
-----------------
// Filter names containing 'sh'
const namesArray = ["samuel"."rahul"."harsh"."hitesh"];
const filterNameArray = namesArray.filter((name) = >{
return name.includes("sh");
});
console.log(filterNameArray);
// ["harsh", "hitesh"]
Copy the code
map()
As the name implies, the map() method is used to map the values of an existing array to new values, push the new values into a new array, and then return the new array. Now map() also needs a callback function, so it is called a higher-order function.
Now, the callback passed to the map() method takes three arguments:
- Element value (required)
- Index of the element (optional)
- Array object (optional)
const numArray = [1.5.3.6.4.7];
const increasedArray = numArray.map((element) = > {
return element + 1;
});
console.log(increasedArray);
[2.6.4.7.5.8]
Copy the code
Just as in filter(), numArray elements will be passed in turn to the map() callback (as the Element argument), they will be mapped to a new value of Element + 1, and they will be put in the increasedArray.
First 1 will be passed as an element parameter and mapped to a new value, element + 1, so that 1 + 1 (since the element here is 1), 2 will be pushed into the increasedArray. Repeat the process for 5, 3, 6, 4 and 7.
Example:
// Index each number in the array
const numArray = [2.3.4.5.15];
const poweredArray = numArray.map((number) = > {
return number * number;
});
console.log(poweredArray);
// [4, 9,16, 25, 144, 225]
// Set the student's score
const studentsArray = [
{
name: "Rahul".marks: 45}, {name: "Samuel".marks: 85}, {name: "Chris".marks: 25,},];const ScoreArray = studentsArray.map((student) = > {
return student.marks;
});
console.log(scoreArray);
/ / [45, 85, 25]
Copy the code
reduce()
The reduce() method is used to reduce an array to a single value. Just like filter() and map(), reduce() requires a callback function as a parameter, so it is called a higher-order function.
But reduce() requires an argument in addition to the callback function, which is an initialValue. Similarly, like filter() and map(), the callback function passed to reduce() requires some arguments, but the callback function passed to reduce() requires four arguments instead of three.
- Initial value (required)
- Element value (required)
- Index of the element (optional)
- Array object (optional)
/ / reduce () sample
const numArray = [1.2.3.4.5];
const sum = numArray.reduce((total, num) = > {
return total + num;
});
console.log(sum);
Copy the code
First, understand what the total argument is. The total argument is the previous value returned by reduce(), and now when reduce() is run for the first time, there will be no previous value returned, So the total argument for the first time is equal to initialValue (the second argument passed to reduce()).
Now that initialValue is not used in the example, what happens when we do not pass initialValue and the reduce() method skips the first element of numArray to the value of the total argument?
In the example, initialValue is not passed, so the first element of numArray, such as 1, will be the value of the total argument, the second element of numArray will be passed as the num argument, and the function will return total + num, If 1 + 2 = 3, 3 will become the new value of total, and now the third element of numArray will be passed as the num argument to the reduce() callback, which will return total + num again, 3 + 3 = 6, and 6 will become the new value of total, And so on.
The above explanation is confusing and confusing, but if you try to learn it gradually, you will master reduce().
InitialValue (initialValue) parameter
InitialValue is the initialValue of the total argument. When reduce() is run for the first time, no previous value is returned, so the first element of the existing array (numArray in the example) becomes the value of the total argument, So instead of giving ·total argument an initialValue (remember that initialValue will be the initialValue of the total argument, which will be the previous return value of reduce()), you can give ·total argument an initialValue.
Note: numArray does not skip its first element when using the initialValue parameter, so each element is passed to the reduce() callback.
Syntax for reduce() with initial values:
const resultantArray = existingArray.reduce((total,element,index.array) = > {
// Return something
}, initialValue);
Copy the code
Thanks for reading!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.