Skip to content
Related Articles

Related Articles

Improve Article

JavaScript TypeError – Reduce of empty array with no initial value

  • Last Updated : 29 Jul, 2020

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.

HTML




<script>
var arr = [1, 2, 3, 4, 5, 6];
arr.filter(x => x < 0)
    // This removes all elements
    .reduce((x, y) => x * y) // TypeError
</script>

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.

HTML




<script>
    var classNm = document.getElementsByClassName("ClassName");
    var GFG_list = 
        Array.prototype.reduce.call(classNm, (a, b) => a + ": " + b);
</script>

Output(in console):

TypeError: reduce of empty array with no initial value
My Personal Notes arrow_drop_up
Recommended Articles
Page :