Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to sum up all the numbers in a range in JavaScript

Abel Lifaefi Mbula


In this shot, we’ll discuss three ways to sum up all the numbers in a given range in JavaScript.

Our program should accept an array of two numbers as input, for example, sumAll([1, 3]). Then, it should process the sum of all the numbers in the given range. It should be noted that both the numbers in the given range are inclusive, that is, 1 and 3 in this example. Finally, the program should return the total/sum as output, which is 6 in the case of this example.

The lowest number will not always come first. Hence, [3,1] should be treated as [1,3].

The workflow of our program

How to use the traditional for loop

function sumAll(arr) {
  if (arr[0] > arr[1]) // if the highest number is on the left, sort the array
    arr.sort((a, b) => a - b)

  let sum = 0 // Initialize a variable that will be holding the sum

  for (let i = arr[0]; i <= arr[1]; i++) // Loop over the range
    sum += i
  return sum // return result

Testing the "for" loop implementation

How to use the .reduce() method

Here we will implement:

  • Generate all the array items in the provided range. For example, [1, 4] => [1, 2, 3, 4].
  • Get the sum by using the reduce() method.
function sumAll(arr) {
  if (arr[0] > arr[1])
    arr.sort((a, b) => a - b)

  const newArr = [] 
  for(let i = arr[0]; i <= arr[1]; i += 1) 

  return newArr.reduce((acc, cur) => acc + cur)

Testing the "reduce()" implementation

We can also use methods other than reduce() to get the sum of the newly created array items.

Happy coding!



View all Courses

Keep Exploring