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!

Why JavaScript Promise Executes Before setTimeout (Event Loop Explained) ?

Many JavaScript developers expect setTimeout(fn, 0) to run before everything else.

But when Promise and setTimeout are together, the output often surprises people.

Let’s understand this using a simple quiz example and a step-by-step explanation.


📌 The Code (Quiz Question)

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

❓ Question:

What will be the output?

A) Start End Timeout Promise
B) Start Promise End Timeout
C) Start End Promise Timeout
D) Start Timeout Promise End

Correct Answer: C) Start End Promise Timeout


🧠 Step-by-Step Execution (Very Important)

To understand this output, you need to know how JavaScript event loop works.

JavaScript uses:

  • Call Stack
  • Microtask Queue
  • Task Queue
  • Event Loop

Let’s go line by line.


🔹 Step 1: Synchronous Code Runs First

console.log("Start");

➡️ Output:

Start


🔹 Step 2: setTimeout Goes to Task Queue

setTimeout(() => {
  console.log("Timeout");
}, 0);

Even with 0ms, the callback:

  • Does NOT execute immediately
  • Goes to the Task Queue

🔹 Step 3: Promise Goes to Microtask Queue

Promise.resolve().then(() => {
  console.log("Promise");
});

This callback goes into the Microtask Queue.

⚠️ Important:

Microtasks always have higher priority than tasks.


🔹 Step 4: Continue Synchronous Code

console.log("End");

➡️ Output so far:

Start
End


🔹 Step 5: Event Loop Priority Rules

After synchronous code finishes:

1️⃣ Event loop executes all microtasks first
2️⃣ Then executes tasks (setTimeout)

So execution order:

  • Promise callback
  • setTimeout callback

🧾 Final Output

Start
End
Promise
Timeout

✔️ Correct option: C


⚡ Key Rule to Remember (Interview Gold)

Microtasks (Promises) always run before Macrotasks (setTimeout).


🧠 Simple Real-World Analogy

Imagine a company office 🏢

  • Regular tasks → Emails (setTimeout)
  • Urgent tasks → Phone calls (Promise)

Even if email is scheduled early, phone calls are answered first.

👉 Promise = urgent
👉 setTimeout = regular


❌ Common Misunderstanding

setTimeout(fn, 0) runs immediately
❌ Promise waits for setTimeout

✅ Truth:

  • Promise → Microtask queue
  • setTimeout → Task queue
  • Microtasks always win

🎯 Interview Tip

If asked:

“Why does Promise execute before setTimeout?”

Answer:

Because Promise callbacks go into the microtask queue, and the event loop always processes microtasks before macrotasks.

React useEffect Explained Clearly (With Simple Examples)

If you are learning React, chances are useEffect confused you at least once.

Questions like:

  • Why does useEffect run twice?
  • When should I use it?
  • What is dependency array?
  • How is it different from lifecycle methods?

Don’t worry.
In this post, I’ll explain useEffect in the simplest way possible, using real-world analogies and clear examples.


What is useEffect in React?

👉 useEffect is used to perform side effects in React components.

Side effects include:

  • Fetching data from an API
  • Updating the DOM
  • Setting timers
  • Subscribing to events
  • Logging data

Simply put:

useEffect runs code when something changes in your component.


Basic Syntax of useEffect

useEffect(() => {
  // side effect code
}, []);

It has two parts:

  1. Effect function – what you want to do
  2. Dependency array – when you want to do it

Case 1: useEffect Without Dependency Array

useEffect(() => {
  console.log("Component rendered");
});

What happens?

✅ Runs after every render

⚠️ Usually not recommended, can cause performance issues.


Case 2: useEffect With Empty Dependency Array []

useEffect(() => {
  console.log("Component mounted");
}, []);

What happens?

✅ Runs only once, after first render

Equivalent to:

componentDidMount()

👉 Most common use case: API calls


Example: Fetching Data

useEffect(() => {
  fetch("/api/users")
    .then(res => res.json())
    .then(data => setUsers(data));
}, []);

✔️ Fetches data only once
✔️ Avoids infinite loops


Case 3: useEffect With Dependencies

useEffect(() => {
  console.log("Count changed");
}, [count]);

What happens?

✅ Runs only when count changes

👉 Useful for reacting to state or prop changes


Example: Search Input

useEffect(() => {
  fetchResults(searchText);
}, [searchText]);

✔️ Runs only when user types
✔️ Optimized & efficient


Cleanup Function in useEffect 🧹

Some effects need cleanup.

Example:

  • Timers
  • Event listeners
  • Subscriptions
useEffect(() => {
  const timer = setInterval(() => {
    console.log("Running...");
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);

👉 Cleanup runs when:

  • Component unmounts
  • Dependencies change

Why Does useEffect Run Twice in React?

In React Strict Mode (development):

  • React runs effects twice
  • This helps detect bugs

🚨 It does NOT happen in production


Common Mistakes with useEffect ❌

❌ Missing dependency array

useEffect(() => {
  setCount(count + 1);
});

➡️ Causes infinite loop


❌ Incorrect dependencies

useEffect(() => {
  fetchData();
}, []);

But fetchData uses props/state → bug!


When Should You Use useEffect?

Use useEffect when:
✅ You interact with outside world
✅ You perform side effects
❌ Not for simple calculations


Summary Table 📌

ScenarioDependency
Run once[]
Run on every renderNo array
Run on change[state/props]
Cleanup neededreturn () => {}

Final Thoughts

If you remember just one line, remember this:

useEffect syncs your React component with the outside world.

Mastering useEffect will:

  • Improve performance
  • Prevent bugs
  • Make you a better React developer

How to convert first letter of the word to UpperCase in JavaScript ?

We can convert the first letter of the word to uppercase by using chatAt and slice methods as follows.

Here, charAt(0).toUpperCase will convert the first letter of the word to uppercase and word.slice(1) will return the remaining characters of the word except first letter.

How to find smallest number with the highest frequency in the array ? – JavaScript

We have multiple approaches to find smallest number with the highest frequency.

1. Using Object.entries :

Explaination:

We got output as 2 because 2 appeared three times (2’s frequency is three). for 3 also we are having frequency three. But we need to find the smallest number with the highest frequency. So Answer is 2.

Above code gives output as { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }. Here this object is in the form of key, value pairs, Where Keys are the given numbers in the array and values are their counts. acc[val] || 0 returns undefined values as 0 and + 1 increments the count.

When we wrap the above code inside Object.entries, it returns an Array of arrays as follows. [ [ ‘1’, 2 ], [ ‘2’, 3 ], [ ‘3’, 3 ], [ ‘4’, 2 ], [ ‘5’, 1 ] ]

Finally we are finding highest frequency. If multiple numbers have the same frequency then we are choosing the smallest number by applying the reduce method.

Above code gives output as [ ‘2’, 3 ]. From here we need to extract the value 2. So we are using [0]. and it will give ‘2’ and then finally we are converting string to number by using console.log(Number(result)).

2. Using step by step Approach :

The following code counts frequency and gives this output : { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }

Next we will find max frequency which is 3 with the following line of code

Finally we will filter by max frequency and find smallest number with the following code.