Explain Codes LogoExplain Codes Logo

How to generate range of numbers from 0 to n in ES2015 only?

javascript
promises
callbacks
lazy-evaluation
Alex KataevbyAlex Kataev·Feb 17, 2025
TLDR

Generate a 0-to-n range in ES6 using [...Array(n).keys()] to create an array of numbers:

const range = [...Array(n).keys()]; // Pikachu, I choose you! This will pick all n

Replace n with your desired end number. The keys() method returns an iterator for the values in the newly minted array of size n.

Expanded solutions and practical tips

Range function: A pinch of Python in JavaScript

Create a range function akin to Python's for easier day to day use. Handles custom start, end, and step values:

const range = (start, end, step = 1) => Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step); // Array.from(), our trusty Transformer, shape-shifts our inputs into a range!

Generators: Keeping ranges in check

Create ranges on-demand with ES6 generators, perfect for larger scenarios where efficiency is paramount:

function* lazyRange(end, start = 0, step = 1) { for (let i = start; i < end; i += step) { yield i; // I give you... a number! 🧙 } } // Use this spell for large ranges or... dare I say, infinite sequences? 🌌

TypeScript compliance: Because TypeScript cares

Using TypeScript? Employ Array.from() instead of the spread syntax variant to avoid compiler complaints:

const range = Array.from(Array(n).keys()); // TypeScript says, "Spectacular! This compiles cleanly."

More tricks up our sleeve: One-liners and esoteric insights

One-liners: Dude, where's my range?

For conciseness, you can use these one-liners:

const range = Array.from(Array(n), (_, i) => i); // or const range = Array(n).fill().map((_, i) => i); //Chef Ramsay: "Finally, some good code"

It's iterable, it's a class

Class syntax in ES2015 lets you create iterable classes for comprehensive range objects:

class Range { constructor(start, end) { this.start = start; this.end = end; } *[Symbol.iterator]() { for (let i = this.start; i <= this.end; i++) { yield i; // It's raining numbers! Hallelujah! 🌧️🌧️ } } }

Avoiding Pitfalls: Tread with caution

  • Performance: High-number ranges can be a drag. Use lazy evaluation.
  • Memory: Large ranges can gobble up memory like a hungry Pac-Man. Opt for generators.
  • TypeScript: Implicit any types can occur. Specify array types explicitly.
  • Sparse arrays: Be careful with methods creating sparse arrays to avoid surprises.