Skip to content
the poor coder

sum range javascript

Poor Man
Published
Reading time
2 min read
On this page

Sum Range in JavaScript#

If you want to sum a range of numbers in JavaScript, you can do it in a number of ways. One way is to use a for loop to iterate over the range and sum the values. Another way is to use the reduce method of an array to sum the values.

Using a For Loop#

To sum a range of numbers using a for loop, you first need to define the range. For example, let's say you want to sum the range from 1 to 10:

Text
var start = 1;
var end = 10;
var sum = 0;

for (var i = start; i <= end; i++) {
  sum += i;
}

console.log(sum); // Output: 55

In this code, we define the start and end of the range, as well as a variable to hold the sum. We then use a for loop to iterate over the range and add each value to the sum. Finally, we log the sum to the console.

Using the Reduce Method#

The reduce method of an array can also be used to sum a range of numbers. To do this, you can create an array containing the range, and then call the reduce method, passing in a function that adds each value:

Text
var range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var sum = range.reduce(function(total, num) {
  return total + num;
});

console.log(sum); // Output: 55

In this code, we create an array containing the range from 1 to 10. We then call the reduce method, passing in a function that adds each value to a total. The reduce method returns the final total, which we log to the console.

Conclusion#

Both of these methods can be used to sum a range of numbers in JavaScript. Which one you choose may depend on your specific use case and personal preference.

Using the for loop may be better for smaller ranges, while using the reduce method may be more efficient for larger ranges.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC