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
We will use the below formula to solve this problem −
Sum of all natural number upto n =
((n*(n+1))/2)
Example
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));Output
And the output in the console will be −
15 28 1035 3 36 4950