An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
What is .reduce(), and how does it work
Have you ever wandered what is .reduce()
function in Javascript? Then this tutorial is for you! Today we will look at how .reduce()
works, and what does it do.
About .reduce()
In Javascript, reduce()
method is used on arrays, it cycles through every element of an array, and for each it executes a function that you have provided in the method.
How to use
.reduce()
has 2 parameters, which are:
- 1. Callback Function
- 2. Initial Accumulator Value
array.reduce(callbackFunction, initialValue)
Callback method has 4 parameters, which are:
- 1. Accumulator
- 2. Current Element
- 3. Index of Current Element
- 4. Array Method is Used on
array.reduce(() => {accunulator, currentElement, index, array} => {})
In todays example, we will not be using last 2 parameters, we will keep it to just Accumulator
(we'll call it a) and Current Element
(we'll call it b).
Throughout each iteration, returned value from callback function is added to the accumulator, which is stored until the end of the iteration and then returned as a single value.
EXAMPLE
const array = [1, 2, 3, 4];console.log(array.reduce((a, b) => a + b))// 1 + 2 + 3 + 4//Logs out "10"console.log(array.reduce((a, b) => a + b, 10))// 10 + 1 + 2 + 3 + 4//Logs out "20"
As you can see above, we reduced an array by adding all of the values up into one, single number. If initial values is not provided, then array will take first element's value, and start iteration from the index of 1. If array is empty, then it will throw a TypeError
stating Reduce of empty array with no initial value
. Although if array only has only one element, then it will return an element, without calling the callback function.
Thanks for reading this post, if you found it helpful then feel free to leave a reaction and or follow for more posts like this, or tutorials on how to make different small things.
Original Link: https://dev.to/agorushkin/what-is-reduce-and-how-does-it-work-20ga
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To