How to generate range of numbers from 0 to n in ES2015 only?
⚡TLDR
Generate a 0-to-n range in ES6 using [...Array(n).keys()]
to create an array of numbers:
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:
Generators: Keeping ranges in check
Create ranges on-demand with ES6 generators, perfect for larger scenarios where efficiency is paramount:
TypeScript compliance: Because TypeScript cares
Using TypeScript? Employ Array.from()
instead of the spread syntax variant to avoid compiler complaints:
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:
It's iterable, it's a class
Class syntax in ES2015 lets you create iterable classes for comprehensive range objects:
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.
Linked
Linked
Was this article helpful?