Skip to content

Sum of numbers from 1 to n JavaScript recursion | Example code

  • by

You don’t need to loop through each pair and add them in recursion. Just use if statement as below example.

Sum of numbers from 1 to n Examples in JS

Let’s see HTML example code:-

Sum of numbers from 1 to n JavaScript recursion

Check the value and if truthy return n plus the sum of n - 1

if the value is smaller than one and returns zero in this case, otherwise the result of the actual value plus the result of calling sum function with a decrement value.

<!DOCTYPE html>
<html> 
<body>


    <script type="text/javascript">
        function sum(n) {
            if (n < 1) return 0;    
            return n  + sum(n - 1); 
        }

        console.log(sum(3));
    </script>

</body>
</html>

Output:

Sum of numbers from 1 to n JavaScript recursion

Without Recursion Example code

Adding numbers between one and a given number without recursion in JavaScript:-

<!DOCTYPE html>
<html> 
<body>


    <script type="text/javascript">
        function sumNums (num) {
          let array = [];
          for (let i = 0; i <= num; i++) {
            array.push(i);
        }
        return array.reduce((a, b) => a + b);
    }

    console.log(sumNums(10)); 

</script>

</body>
</html>

Output:

Sum Numbers Between 1 and a Given Number without Recursion

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