Emmanuel Akinfulubi

JavaScriptArray

Create a range of numbers in JavaScript

Beginner · 4 min read

Many languages have a built-in range that gives you a list of numbers, like 1, 2, 3, 4. JavaScript doesn't, but you will want one often: page numbers for a pager, the years in a dropdown, the hours on a timetable, or just a quick list to loop over.

In this tutorial you will write range(start, end, step). It gives the numbers from start up to, but not including, end, moving by step each time. It will count down when the step is negative, give an empty array when there is nothing to count, and refuse a step of zero. You should know how to write a function. Array.from, Math.ceil and throw are explained below.

Two tools we need

Array.from({ length: n }, fn) makes an array with n slots and calls fn once for each. The second thing fn receives is the index, 0, 1, 2 and so on.

JavaScript

console.log(Array.from({ length: 3 }, (_, i) => i * 10)); // [ 0, 10, 20 ]

Math.ceil rounds a number up to the next whole number. Math.max(a, b) gives the bigger of two numbers.

JavaScript

console.log(Math.ceil(2.1));  // 3
console.log(Math.ceil(-2.5)); // -2
console.log(Math.max(0, -4)); // 0

The plan: count first

Instead of looping until we pass end, we work out how many numbers there will be, then build exactly that many. Number i in the list is start + i * step. This plan handles counting up and counting down with the same code.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

3 A range of numbers

easy

Write range(start, end, step) giving the numbers from start up to but not including end. It has to handle a negative step, an empty range and a step of zero.

Stuck? Three hints, smallest first
  1. 1. Work out the count first, then build that many values with Array.from.
  2. 2. Math.ceil((end - start) / step) is the count, and a negative count means an empty range.
  3. 3. A step of zero would never terminate, so refuse it rather than looping forever.

Step 1: count with step 1

From 1 up to (not including) 5 there are 5 - 1 = 4 numbers.

Step 1

function range(start, end) {
  const count = end - start;
  return Array.from({ length: count }, (_, i) => start + i);
}
console.log(range(1, 5)); // [ 1, 2, 3, 4 ]

Step 2: add a step

With a step, divide the distance by the step. From 0 to 10 in steps of 2 is 10 / 2 = 5 numbers. When it doesn't divide evenly, round up: from 1 to 5 in steps of 10 is 0.4, and we still want the start, so Math.ceil makes it 1.

Step 2

function range(start, end, step = 1) {
  const count = Math.ceil((end - start) / step);
  return Array.from({ length: count }, (_, i) => start + i * step);
}
console.log(range(0, 10, 2));  // [ 0, 2, 4, 6, 8 ]
console.log(range(1, 5, 10));  // [ 1 ]
console.log(range(5, 1, -1));  // [ 5, 4, 3, 2 ]

step = 1 is a default parameter: if nobody passes a step, it is 1. Counting down works for free: (1 - 5) / -1 is 4, so we get four numbers going down.

Step 3: the wrong direction

What if the step points the wrong way, like range(1, -5)? The count is (-5 - 1) / 1, which is -6. An array can't have a negative length, and new Array says so:

Step 3

try {
  new Array(-6);
} catch (e) {
  console.log(e.constructor.name); // RangeError
}
console.log(Array.from({ length: -6 })); // []

Array.from is more forgiving: it quietly treats a negative length as 0. Our code shouldn't lean on that hidden rule, so we say it out loud with Math.max(0, ...), which means "at least zero":

JavaScript

const count = Math.max(0, Math.ceil((-5 - 1) / 1));
console.log(count); // 0

Now anyone reading range can see that a backwards range gives an empty array, and so does range(3, 3), where the distance is zero.

Step 4: refuse a step of zero

A step of zero would never reach the end. Dividing by zero in JavaScript gives Infinity, and Array.from can't make an array that long, so it throws RangeError: Invalid array length. Better to stop early with a clear message. throw stops the function and reports an error. A RangeError is the built-in error for "this number is out of the allowed range".

Step 4

function range(start, end, step = 1) {
  if (step === 0) throw new RangeError('step must not be 0');
  const count = Math.max(0, Math.ceil((end - start) / step));
  return Array.from({ length: count }, (_, i) => start + i * step);
}
console.log(range(3, 3));  // []
console.log(range(1, -5)); // []
try {
  range(1, 5, 0);
} catch (e) {
  console.log(e.message); // step must not be 0
}

That is the whole function. The check comes first, so the bad step never reaches the maths.

Step 5: a shortcut for 0 to n

When you only need 0, 1, 2 up to n - 1, there is a short form you will see in other people's code:

Step 5

console.log([...Array(5).keys()]); // [ 0, 1, 2, 3, 4 ]

Array(5) is an array of length 5 with empty slots, keys() gives its indexes, and the spread [...] collects them into an array. It is handy, but range reads more clearly and handles any start and step.

The full solution

The panel has the finished range and tries it counting up, counting down, on an empty range, the wrong way round and with a zero step. Press Run to see each result.

The answer

function range(start, end, step = 1) {
  if (step === 0) throw new RangeError('step must not be 0');
  const count = Math.max(0, Math.ceil((end - start) / step));
  return Array.from({ length: count }, (_, i) => start + i * step);
}

const refused = (() => {
  try { range(1, 5, 0); return 'no error'; } catch (e) { return e.constructor.name; }
})();

console.log('range(1, 5)      :', range(1, 5));
console.log('range(0, 10, 2)  :', range(0, 10, 2));
console.log('range(5, 1, -1)  :', range(5, 1, -1));
console.log('range(3, 3)      :', range(3, 3), '<- end is excluded, so nothing');
console.log('range(1, -5)     :', range(1, -5), '<- wrong direction for a +1 step');
console.log('step of 0        :', refused);
console.log('the shortcut for range(0, n):', [...Array(5).keys()]);

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.

9 checks

test('the end is excluded', range(1, 5), [1, 2, 3, 4]);
test('a step of 2', range(0, 10, 2), [0, 2, 4, 6, 8]);
test('counting down needs a negative step', range(5, 1, -1), [5, 4, 3, 2]);
test('an empty range', range(3, 3), []);
test('a step bigger than the range still yields the start', range(1, 5, 10), [1]);
test('the wrong direction yields nothing rather than looping', range(1, -5), []);
test('a long range has the length you would expect', range(0, 1000).length, 1000);
test('keys() is the shortcut for 0 to n', [...Array(5).keys()], [0, 1, 2, 3, 4]);
test('a zero step is refused', refused, 'RangeError');

Computing the count up front is what makes the negative step fall out for free: Math.ceil((1 - 5) / -1) is 4, and Math.ceil((-5 - 1) / 1) is negative, which Math.max(0, ...) turns into an empty array. A for loop with i < end would silently produce nothing in one direction and run away in the other.

[...Array(5).keys()] is the shortest form for range(0, n), and it works precisely because keys() is an iterator that does not skip holes.

Common mistakes

  • Including the end. range(1, 5) stops at 4. That matches slice and for (let i = 1; i < 5; i++), so it is the usual choice.
  • Looping while (i < end) with a negative step. The condition is false straight away, so counting down gives nothing. Working out the count first avoids this.
  • Forgetting the zero step. Without the check, range(1, 5, 0) fails with Invalid array length, which doesn't tell you the step was the problem.

Try it yourself

  1. Use range to list the years from 2020 to 2025, including 2025.
  2. Build the odd numbers below 20 with one call to range.
  3. Try range(0, 1, 0.1) and look at the fourth value. Why is it 0.30000000000000004 and not 0.3?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.