Mathematics summation function in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should return the sum of all the natural numbers from 1 to n including both 1 and n

Example

Following is the code −

 Live Demo

const num = 34;
const summation = (num = 1) => {
   let res = 0;
   for(let i = 1; i <= num; i++){
      res += i;
   };
   return res;
};
console.log(summation(num));

Output

Following is the console output −

595

Updated on: 17-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements