Skip to content

JavaScript recursive function array | Compute the sum of an array of integers

  • by

A JavaScript recursive function is a function that calls itself until it doesn’t. It has a condition to stop calling itself, otherwise, it will call itself indefinitely.

JavaScript recursive function array Example code

HTML example code program to compute the sum of an array of integers in JavaScript.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var array_sum = function(my_array) {
          if (my_array.length === 1) {
            return my_array[0];
        }
        else {
            return my_array.pop() + array_sum(my_array);
        }
    };

    console.log(array_sum([1,2,3,4,5,6]));
</script>

</body>
</html>

Output:

JavaScript recursive function array compute sum number example

Do comment if you have any doubts and suggestion on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading