JavaScript TypeError – Reduce of empty array with no initial value
Last Updated :
22 May, 2023
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)
.reduce((x, y) => x * y)
|
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...