JavaScript TypeError – Reduce of empty array with no initial value

This JavaScript exception reduce of empty array with no initial value occurs if a reduce function is used with the empty array.
Message:
TypeError: reduce of empty array with no initial value
Error Type:
TypeError
Cause of Error:
This error is raised if an empty array is provided to the reduce() method because no initial value can be returned in this case.
Example 1: In this example, the filter method removes all elements, So the reduce method applies to empty array and error occurred.
Javascript
| let arr = [1, 2, 3, 4, 5, 6];arr.filter(x => x < 0)    // This removes all elements    .reduce((x, y) => x * y) // TypeError | 
Output(in console):
TypeError: reduce of empty array with no initial value
Example 2: In this example, there is an unexpected number of elements in a list, Which could cause a problem.
Javascript
| let classNm = document.getElementsByClassName("ClassName");let GFG_list =    Array.prototype.reduce.call(classNm, (a, b) => a + ": "+ b); | 
Output(in console):
TypeError: reduce of empty array with no initial value
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					


