sum range javascript

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:

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:

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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe