DEV Community


Sum of nature numbers with Javascript

timhuang profile image Timothy Huang ・1 min read

There are many ways to calculate sum of nature numbers. The basic method is for-loop (a simple way):

function sum1(n){
  var sum = 0;
  for(var i=1;i<=n;i++){
    sum += i;
  return sum;

Another method is recursion. Since the sum is 1 + 2 + .. + n, we can easily get

sum(n) = n + sum(n-1)
and sum(n-1) = n-1 + sum(n-2) ...
until sum(1) = 1.

This also a divide-and-conquer method.

function sum2(n){
    return 1;
    return n + sum2(n-1);

The third way is more complex, using map and reduce. With Javascript, the map function and reduce function are Array methods.

First, we can use map function to create an array as [1, 2, ... n] :

    .map(function(_, index){ 
      return index + 1; 

Second, we can use reduce function to calculate the sum of these numbers:

    .map(function(_, index){ 
      return index + 1; 
    .reduce(function(acc, cur){
      return acc + cur;

Let's play with

Happy coding!

Discussion (0)

Editor guide