- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

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

- Related Questions & Answers
- Count of all N digit numbers such that num + Rev(num) = 10^N - 1 in C++
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Sum of even numbers up to using recursive function in JavaScript
- How to print all the Armstrong Numbers from 1 to 1000 using C#?
- Java Program to Display All Prime Numbers from 1 to N
- Program to find all missing numbers from 1 to N in Python
- Compute sum of digits in all numbers from 1 to n
- Sum of the natural numbers (up to N) whose modulo with K yield R in C++
- Any possible combination to add up to target in JavaScript
- Finding the nth digit of natural numbers JavaScript
- Program to count how many numbers should be appended to create all numbers from 1 to k in C++
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1?
- Print all odd numbers and their sum from 1 to n in PL/SQL
- Program to find duplicate element from n+1 numbers ranging from 1 to n in Python
- Print all increasing sequences of length k from first n natural numbers in C++

Advertisements