How to Find Sum of Array Using reduce() in JavaScript (Step-by-Step Execution Explained)

Finding the sum of array elements is one of the most common tasks in JavaScript.
While there are multiple ways to do it, the reduce() method is the most powerful and preferred approach.

In this post, you’ll learn:

  • What reduce() is ?
  • How to use it to find sum
  • Step-by-step execution (very important)
  • What happens if you don’t provide initial value
  • Common mistakes to avoid

Let’s get started 👇


What is reduce() in JavaScript?

The reduce() method is used to:

Convert an array into a single value

This value can be:

  • Sum
  • Product
  • Object
  • String

Problem Statement

Write a JavaScript program to find the sum of array elements using reduce().


Basic Example

const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 100

Understanding the Syntax

array.reduce((acc, curr) => acc + curr, initialValue);

Parameters:

  • acc → accumulator (stores result)
  • curr → current element
  • initialValue → starting value (important!)

Step-by-Step Execution (Very Important)

Let’s understand how this works internally.

Input:

[10, 20, 30, 40]

Code:

numbers.reduce((acc, curr) => acc + curr, 0);

Execution Flow Table

StepacccurrOperationResult
10100 + 1010
2102010 + 2030
3303030 + 3060
4604060 + 40100

Final Output

100

How reduce() Works Internally

You can think of reduce() like this:

let acc = 0;for (let i = 0; i < numbers.length; i++) {
acc = acc + numbers[i];
}

👉 It keeps updating the acc value until all elements are processed.


What Happens If You Don’t Provide Initial Value?

numbers.reduce((acc, curr) => acc + curr);

Execution Without Initial Value

StepacccurrResult
Start102030
Next303060
Next6040100

👉 Here:

  • acc starts as first element (10)
  • Loop starts from second element (20)

Problem with Empty Array

[].reduce((acc, curr) => acc + curr);

👉 💥 Error:

TypeError: Reduce of empty array with no initial value

Link : TypeError: Reduce of Empty Array with No Initial Value (Fix Explained)


Best Practice

Always use initial value:

numbers.reduce((acc, curr) => acc + curr, 0);

Common Mistakes

1. Forgetting initial value

👉 Can cause errors


2. Using map() instead of reduce()

👉 Wrong approach for sum


3. Not understanding execution flow

👉 Leads to confusion in interviews


Real-World Use Cases

  • Shopping cart total
  • Marks calculation
  • Financial reports
  • Data aggregation

Interview Tip

If asked:

“How does reduce work?”

Answer:

“It iterates over each element, updates an accumulator value, and finally returns a single result.”


Related Articles (Internal Linking)

👉 You can also check:


Final Summary

  • reduce() converts array → single value
  • acc stores result
  • curr is current element
  • Always use initial value (0)
  • Helps in writing clean and efficient code

💡 Found this helpful? Subscribe to get simple JavaScript explanations, interview questions, and real-world coding tips directly in your inbox. Happy Coding!

TypeError: Reduce of Empty Array with No Initial Value (Fix Explained)

While working with JavaScript arrays, you might have seen this error:

TypeError: Reduce of empty array with no initial value

This error is very common, especially when using the reduce() method.

In this post, we’ll understand:

  • What this error means
  • Why it happens
  • How to fix it properly
  • Best practices to avoid it

All explained in a simple and clear way.


What is reduce()?

Before understanding the error, let’s quickly recap:

reduce() is used to:

Convert an array into a single value (sum, object, etc.)

Example:

const numbers = [10, 20, 30];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 60

The Error

Now look at this:

[].reduce((acc, curr) => acc + curr);

👉 Output:

TypeError: Reduce of empty array with no initial value

Why Does This Error Occur?

To understand this, you must know how reduce() works internally.


Case 1: Without Initial Value

[10, 20, 30].reduce((acc, curr) => acc + curr);

Internally:

  • acc = 10 (first element)
  • curr = 20 (second element)

Then continues…


Problem with Empty Array

Now consider:

[].reduce((acc, curr) => acc + curr);

There is:

  • ❌ No first element
  • ❌ No second element
  • ❌ Nothing to assign to acc

👉 JavaScript gets confused and throws an error.


Root Cause

reduce() needs an initial value or at least one element to start with.

If both are missing → 💥 Error


Solution 1: Always Provide Initial Value

[].reduce((acc, curr) => acc + curr, 0);

👉 Output:

0

Why this works:

  • acc = 0 (initial value)
  • No elements → loop doesn’t run
  • Returns 0

Solution 2: Check Array Before Reduce

function sumArray(arr) {
if (arr.length === 0) return 0;
return arr.reduce((acc, curr) => acc + curr);
}

Solution 3: Safe Reduce Pattern

const sum = (arr || []).reduce((acc, curr) => acc + curr, 0);

👉 Handles:

  • null
  • undefined
  • empty array

Real-World Scenario

Imagine:

const cartItems = [];

You calculate total:

const total = cartItems.reduce((sum, item) => sum + item.price);

💥 App crashes if cart is empty!


Correct Approach

const total = cartItems.reduce((sum, item) => sum + item.price, 0);

Common Mistake Developers Make

❌ Forgetting initial value:

arr.reduce((acc, curr) => acc + curr);

✅ Correct:

arr.reduce((acc, curr) => acc + curr, 0);

Best Practice

Always provide an initial value when using reduce()


Simple Analogy

Imagine you are adding numbers:

  • If someone gives you numbers → you can start
  • If no numbers are given → what will you add? 🤔

👉 You need a starting value (like 0)


With vs Without Initial Value

CaseBehavior
With initial valueSafe, works always
Without initial valueFails for empty array

Interview Tip

If asked:

Why does this error occur?

Answer:

The error occurs because reduce() tries to use the first element as the accumulator, but in an empty array, no such element exists. Providing an initial value solves this issue.


🏁 Final Summary

  • reduce() combines array elements into one value
  • Without initial value:
    • Uses first element as accumulator
    • Fails for empty arrays
  • With initial value:
    • Safe and predictable
    • Works for all cases

👉 Always use an initial value to avoid this error

💡 Found this helpful? Subscribe to get real-world coding tips, interview questions, and easy explanations directly in your inbox. Happy Coding!