JavaScript

Range Generator

by @admin
12h ago
Apr 28, 2026
Public
Generates an array of numbers from start to end (inclusive) with an optional step. Supports negative steps for counting down. Covers the most common use case of Array.from({ length: n }, (_, i) => i) with a much cleaner API, and handles arbitrary start/end/step combinations.
JavaScript
function range(start, end, step = 1) {
  const result = [];
  if (step === 0) throw new Error('step cannot be 0');
  for (let i = start; step > 0 ? i <= end : i >= end; i += step) {
    result.push(i);
  }
  return result;
}

// Usage
console.log(range(1, 5));        // [1, 2, 3, 4, 5]
console.log(range(0, 10, 2));   // [0, 2, 4, 6, 8, 10]
console.log(range(5, 1, -1));   // [5, 4, 3, 2, 1]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.