JavaScript Reduce Method Explained with Practical Examples
See how JavaScript reduce turns an array of prices into a single total, and learn the callback pattern you can reuse for sums and other accumulations.


javascript reduce is generally used for mathematical operations. You can think of it as, for example, getting the sum of the numbers in an array. We can explain this with an example below. The first thing we need to do is create the function we’ll use together with reduce. In our example, let’s create a function that rounds the numbers and lets us get their sum.
var sayilar = [12.2,22,1,4,4,5,8];
function yuvarlaTopla(toplam,sayi){
return toplam = Math.round(sayi);
}
console.log( sayilar.reduce(yuvarlaTopla,0));
//when our function above runs, you'll see the result 8 in the console.
When javascript array reduce starts running, it will make a function call for as many elements as there are in the array. When this process starts, if the initial value for the array is empty, you may run into an error; in that case, what we need to do is define 0 as the initial value.
- Using javascript break and continue
- Using Javascripit Array Map
- Using js if else
- What Is a Javascript For Loop and How Is It Used?
- What Are Js SHIFT and UNSHIFT and How Are They Used?
- Using Javascript Split and Join
In addition, you can reach the official javascript site here.
Share it if it helped


