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.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output(in console):

TypeError: reduce of empty array with no initial value

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.