JavaScript Snippet

Generate a Numeric Range

Difficulty: Easy

JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.

Code Snippets
/

Generate a Numeric Range

Generate a Numeric Range

JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.

JavaScript
Easy
3 snippets
arrays
utility
generators
code-template

1,186 views

14

Array.from({ length: n }, mapFn) is the cleanest way to materialise a sized array in JavaScript. The first argument is an array-like with just a length property, and the optional mapFn is invoked for each index. The pattern is more readable than [...Array(n).keys()] once you see it a few times, and it handles n = 0 by returning [] without special casing. This is the version you want for the 90% case where you just need indices 0 through n - 1.