Range of integers using recursion in JavaScript
Beginner · 3 min read
Listing the numbers between two values sounds like a job for a loop, and usually it is. Writing it with recursion is a great first recursive exercise, though, because the function builds an array piece by piece and you can watch every piece arrive. Page numbers, seat rows and year pickers all start from a list like this.
In this tutorial you will write range(x, y) so that range(2, 9) returns [3, 4, 5, 6, 7, 8]. You need to know what an array is and what a function is. Recursion and the spread syntax are both explained below.
Read the example before the name
Look closely at the expected output. range(2, 9) gives [3, 4, 5, 6, 7, 8]. Neither 2 nor 9 is in it. That is unusual: in most languages a "range" includes at least the start. Here the task asks for the numbers strictly between the two ends, so that is what we build. When a name and an example disagree, follow the example.
Two tools: recursion and spread
A recursive function calls itself on a smaller version of the problem, and stops at a base case that it can answer straight away.
The spread syntax ... unpacks an array's items into a new array:
const tail = [4, 5];
console.log([3, ...tail]); // [ 3, 4, 5 ]
console.log([3, ...[]]); // [ 3 ]
Spreading an empty array adds nothing. That small fact makes the whole solution work.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
3 The integers between two numbers
easyReturn the whole numbers strictly between x and y. The question is explicit: range(2, 9) gives [3, 4, 5, 6, 7, 8].
Stuck? Three hints, smallest first
- 1. Read the expected output carefully: both ends are left out. That is unusual.
- 2. The base case returns an empty array, and spreading an empty array adds nothing.
- 3.
[x + 1, ...range(x + 1, y)]builds it from the front.
Step 1: the base case
When is there nothing between x and y? When the next number after x already reaches y. For range(8, 9), the next number is 9, so the answer is an empty array.
function range(x, y) {
if (x + 1 >= y) return [];
return 'not done yet';
}
console.log(range(8, 9)); // []
console.log(range(5, 5)); // []
Step 2: build from the front
If there is room, the first number in the answer is x + 1. Everything after it is the range from x + 1 to y, which is a smaller version of the same problem:
function range(x, y) {
if (x + 1 >= y) return [];
return [x + 1, ...range(x + 1, y)];
}
console.log(range(2, 9)); // [ 3, 4, 5, 6, 7, 8 ]
console.log(range(4, 6)); // [ 5 ]
Here is how range(5, 8) unfolds. Each call puts one number in front of whatever the next call returns:
range(5, 8) = [6, ...range(6, 8)]
range(6, 8) = [7, ...range(7, 8)]
range(7, 8) = []
so range(6, 8) is [7] and range(5, 8) is [6, 7]
Step 3: why >= and not ===
A first try often uses x + 1 === y as the base case. It works for range(2, 9). But call it backwards:
function rangeBad(x, y) {
if (x + 1 === y) return [];
return [x + 1, ...rangeBad(x + 1, y)];
}
try {
rangeBad(9, 2);
} catch (e) {
console.log(e.constructor.name); // 'RangeError'
}
x starts above y and only grows, so x + 1 never equals y. The calls pile up until JavaScript throws RangeError: Maximum call stack size exceeded. The >= check ends the recursion normally and catches backwards input:
function range(x, y) {
if (x + 1 >= y) return [];
return [x + 1, ...range(x + 1, y)];
}
console.log(range(9, 2)); // []
Step 4: the inclusive version
Sometimes you do want both ends. Change the base case to "start is past the end" and put x itself in front:
const rangeInclusive = (x, y) => (x > y ? [] : [x, ...rangeInclusive(x + 1, y)]);
console.log(rangeInclusive(2, 9)); // [ 2, 3, 4, 5, 6, 7, 8, 9 ]
It is two items longer than range(2, 9): the 2 and the 9.
Step 5: the same thing without recursion
For real code, Array.from makes the list in one call. { length: n } says how many items you want, and the function works out each item from its position i:
const rangeBuiltIn = (x, y) => Array.from({ length: Math.max(0, y - x - 1) }, (_, i) => x + 1 + i);
console.log(rangeBuiltIn(2, 9)); // [ 3, 4, 5, 6, 7, 8 ]
console.log(rangeBuiltIn(9, 2)); // []
Math.max(0, ...) stops a backwards call from asking for a negative length.
The full solution
The panel has the exclusive range, the inclusive version and the Array.from version, with checks for adjacent, equal and backwards inputs. Press Run to see the output.
// Both ends excluded: range(2, 9) is [3..8], matching the example.
function range(x, y) {
if (x + 1 >= y) return []; // nothing in between
return [x + 1, ...range(x + 1, y)];
}
// The inclusive version most other languages mean by "range".
const rangeInclusive = (x, y) => (x > y ? [] : [x, ...rangeInclusive(x + 1, y)]);
// No recursion at all, for comparison.
const rangeBuiltIn = (x, y) => Array.from({ length: Math.max(0, y - x - 1) }, (_, i) => x + 1 + i);
console.log('range(2, 9) =', range(2, 9));
console.log('rangeInclusive(2, 9) =', rangeInclusive(2, 9));
console.log('range(2, 3) =', range(2, 3), '<- adjacent, so nothing between');
console.log('range(9, 2) =', range(9, 2), '<- backwards, so nothing at all');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example", range(2, 9), [3, 4, 5, 6, 7, 8]);
test('neither end is included', range(2, 9).includes(2) || range(2, 9).includes(9), false);
test('adjacent numbers give nothing', range(2, 3), []);
test('equal numbers give nothing', range(5, 5), []);
test('backwards gives nothing, not an endless loop', range(9, 2), []);
test('one number between', range(4, 6), [5]);
test('the built-in version agrees', rangeBuiltIn(2, 9), range(2, 9));
test('the inclusive version keeps both ends', rangeInclusive(2, 9), [2, 3, 4, 5, 6, 7, 8, 9]);
test('and is two longer', rangeInclusive(2, 9).length - range(2, 9).length, 2);
The interesting part of this one is reading the specification instead of the name. "Range" almost everywhere else includes at least the start — Python's range(2, 9) is 2..8 — but the stated output excludes both ends, so that is what the assertions check. The x + 1 >= y guard is also doing double duty: it ends the recursion normally and it stops a backwards call from recursing forever.
Common mistakes
- Including the ends. The task's example leaves out both 2 and 9. Check your output against it.
- Using
===in the base case. A backwards call likerange(9, 2)then never stops. - Returning
xinstead ofx + 1first. That puts the start into the list, which this version must not include.
Try it yourself
- Write
rangeStep(x, y, step)that counts up in steps, sorangeStep(0, 10, 2)gives[0, 2, 4, 6, 8, 10]. - Make
rangecount down whenxis bigger thany, sorange(9, 5)gives[8, 7, 6]. - Write
sumBetween(x, y)that adds up the numbers strictly betweenxandywithout building an array at all.