Function to add up all the natural numbers from 1 to num in JavaScript

We are required to write a JavaScript function that takes in a number, say num.

Then our function should return the sum of all the natural numbers between 1 and num, including 1 and num.

For example, if num is ?

const num = 5;

Then the output should be ?

const output = 15;

because,

1+2+3+4+5 = 15

The Mathematical Formula

We will use the efficient mathematical formula to solve this problem ?

Sum of all natural numbers up to n =

((n*(n+1))/2)

This formula is much more efficient than using loops, especially for large numbers.

Using the Mathematical Formula

The code for this will be ?

const num = 5;
const sumUpto = num => {
    const res = (num * (num + 1)) / 2;
    return res;
};
console.log(sumUpto(num));
console.log(sumUpto(7));
console.log(sumUpto(45));
console.log(sumUpto(2));
console.log(sumUpto(8));
console.log(sumUpto(99));
15
28
1035
3
36
4950

Alternative: Using a Loop

For educational purposes, here's how you could solve it using a loop:

const sumUptoLoop = num => {
    let sum = 0;
    for (let i = 1; i <= num; i++) {
        sum += i;
    }
    return sum;
};

console.log(sumUptoLoop(5));
console.log(sumUptoLoop(10));
15
55

Comparison

Method Time Complexity Space Complexity Best For
Mathematical Formula O(1) O(1) Production code
Loop Method O(n) O(1) Learning purposes

Conclusion

The mathematical formula approach is the most efficient way to sum natural numbers from 1 to n. It provides constant time complexity and is the preferred method for production applications.

Updated on: 2026-03-15T23:19:00+05:30

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements