Finding sum of all numbers within a range in JavaScript

Problem

We are required to write a JavaScript function that takes in an array that specifies a range.

Our function should find and return the sum of all the natural numbers falling in the range including the range numbers.

Example

Following is the code ?

const range = [4, 67];
const findSum = ([l, h]) => {
    let sum = 0;
    for(let i = l; i 

Output

Following is the console output ?

2272

Using Mathematical Formula (Optimized)

For better performance with large ranges, we can use the mathematical formula for sum of consecutive numbers:

const findSumOptimized = ([l, h]) => {
    // Formula: Sum = n * (first + last) / 2
    // where n is count of numbers
    const count = h - l + 1;
    return count * (l + h) / 2;
};

console.log(findSumOptimized([4, 67]));   // Same result
console.log(findSumOptimized([1, 100]));  // Sum 1 to 100
2272
5050

Handling Edge Cases

Here's a more robust version that handles various edge cases:

const findSumRobust = (range) => {
    if (!Array.isArray(range) || range.length !== 2) {
        return 0;
    }
    
    let [l, h] = range;
    
    // Ensure l is smaller than h
    if (l > h) {
        [l, h] = [h, l];
    }
    
    const count = h - l + 1;
    return count * (l + h) / 2;
};

console.log(findSumRobust([67, 4]));    // Reversed range
console.log(findSumRobust([5, 5]));     // Single number
console.log(findSumRobust([]));         // Invalid input
2272
5
0

Comparison

Method Time Complexity Best For
Loop Method O(n) Small ranges, educational purposes
Mathematical Formula O(1) Large ranges, performance-critical code

Conclusion

While the loop method is intuitive, the mathematical formula provides constant-time performance. For large ranges, always prefer the optimized approach using the sum formula.

Updated on: 2026-03-15T23:19:00+05:30

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements