Sum a range of numbers/javascript

Donovan
2 min readAug 27, 2021

Looking to find the sum of all numbers between two integers? I got you.

I love loops. For this problem I have used two “for” loops to solve the problem although there, as always, has to be a better way.

We will first need to create a variable, “nums”, that points to an empty array that we can push numbers to. After we create this variable we will use the first “for” loop to push all numbers between the two values into that array.

Assuming the two values were given to us as arguments we will call them “a’ and “b”. The first goal will be achieved by writing our “for” loop as such:

This loop is counting up from value a to value b and is storing each value in the nums array.

Now that you have an array of all numbers from value a to value b the next step is writing a for loop that will sum all of the integers in the array. You will need to create a variable that you will be able to add to. It needs to be in scope of the entire function so declare it where you declared the nums array.

Our second “for” loop will look ver similar:

for(i=0; i<nums.length; i++){sum = sum+nums[i]}

This loop is making a counter start at 0, comparing it to the length of the nums array we created, and incrementing i by one until it reaches the length of our array. For each increment until the length of the array we are reassigning our variable sum to equal itself PLUS the next value and so on until the loop is over.

Then be sure to return the sum variable. Happy Coding.

--

--

Donovan

Learning. Puttin up shots in Angular and Java and Python and anything else I get my hands on. Sights set on becoming a gainfully employed developer.