Returning array of natural numbers between a range in JavaScript

We need to write a JavaScript function that takes an array of two numbers [a, b] (where a ? b) and returns an array containing all natural numbers within that range, including the endpoints.

Problem

Given a range specified by two numbers, we want to generate all natural numbers between them. Natural numbers are positive integers starting from 1.

Using a For Loop

The most straightforward approach uses a for loop to iterate through the range and build the result array:

const range = [6, 10];

const naturalBetweenRange = ([lower, upper] = [1, 1]) => {
    if (lower > upper) {
        return [];
    }
    
    const result = [];
    for (let i = lower; i <= upper; i++) {
        result.push(i);
    }
    return result;
};

console.log(naturalBetweenRange(range));
[ 6, 7, 8, 9, 10 ]

Using Array.from() Method

A more concise approach uses Array.from() with a mapping function:

const generateRange = ([start, end]) => {
    if (start > end) return [];
    
    return Array.from(
        { length: end - start + 1 }, 
        (_, index) => start + index
    );
};

console.log(generateRange([3, 8]));
console.log(generateRange([15, 20]));
[ 3, 4, 5, 6, 7, 8 ]
[ 15, 16, 17, 18, 19, 20 ]

Using Spread Operator with Array.keys()

Another elegant solution combines the spread operator with Array.keys():

const createRange = (start, end) => {
    if (start > end) return [];
    
    return [...Array(end - start + 1).keys()].map(i => i + start);
};

console.log(createRange(1, 5));
console.log(createRange(10, 15));
[ 1, 2, 3, 4, 5 ]
[ 10, 11, 12, 13, 14, 15 ]

Comparison

Method Readability Performance Memory Usage
For Loop High Best Efficient
Array.from() Medium Good Moderate
Spread + keys() Medium Good Moderate

Edge Cases

Handle invalid ranges gracefully:

const safeRange = ([start, end]) => {
    // Handle invalid input
    if (start > end || start < 1 || end < 1) {
        return [];
    }
    
    const result = [];
    for (let i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
};

console.log(safeRange([5, 3]));  // Invalid: start > end
console.log(safeRange([0, 5]));  // Invalid: start < 1
console.log(safeRange([2, 6]));  // Valid range
[]
[]
[ 2, 3, 4, 5, 6 ]

Conclusion

The for loop approach offers the best performance for generating natural number ranges. Use Array.from() for more functional programming style, and always validate input ranges to handle edge cases properly.

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

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements