Explain Codes LogoExplain Codes Logo

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

javascript
promises
callbacks
functional-programming
Nikita BarsukovbyNikita Barsukov·Feb 5, 2025
TLDR

Looking for a quick numeric range in JavaScript? Here's your one-stop solution using Array.from():

const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);

Invoke range(1, 5) to get [1, 2, 3, 4, 5]. Talk about efficiency's twin brother, simplicity!

Preparing for larger battles

Now, let's expand our toolkit by building a step increment and orchestrating character ranges.

March with step control

Want to march a different beat? Our function can do just that:

const range = (start, end, step = 1) => Array.from({ length: Math.ceil((end - start + 1) / step) }, (_, i) => i * step + start);

Now you can whistle through range(1, 10, 2) yielding [1, 3, 5, 7, 9]. It's like having a three-legged race!

Generate an alphabet soup

Suddenly craving an alphabet soup? Fear not, for javascript is here:

const characterRange = (startChar, endChar) => Array.from({ length: endChar.charCodeAt(0) - startChar.charCodeAt(0) + 1 }, (_, i) => String.fromCharCode(i + startChar.charCodeAt(0)));

Invoke characterRange('A', 'E') and voila! ['A', 'B', 'C', 'D', 'E'] — a bit drafty for an alphabet soup, isn't it?

Embracing TypeScript? We've got you covered!

For the TypeScript fans out there, there's something in our bag for you;

function typedRange(start: number, end: number): Array<number> { return range(start, end); }

Our function gives back a tidy array of numbers, leaving the burden of mixed-type arrays to the uncivilized!

Stepping into the utility belt

lodash to the rescue!

Fancy a ready-to-use utility belt? lodash's _.range() function has you covered:

const lodashNumericRange = _.range(1, 6); // Numeric Assembly Line: [1, 2, 3, 4, 5]

Craving for some alphabets? lodash delivers with ease:

// An A to Z of characters. Perfect for a spelling bee! const lodashCharRange = _.range('A'.charCodeAt(0), 'Z'.charCodeAt(0) + 1).map(x => String.fromCharCode(x)); // ['A', 'B', ..., 'Z']

Functional programming beauty

// Once you go functional, you never go un-ctional

Let's employ functional programming principles to generate sequences:

// Like a transformer that got a job at an assembly line const range = (start, end) => Array(end - start + 1).fill().reduce((acc, _, idx) => [...acc, start + idx], []);

Admire the elegance as .reduce() weaves every stitch in the fabric of our range.

Backwards compatibility for the sentimental

For those of us nostalgic of the good ol' browser versions, Array.apply() is the bridge:

const oldBrowserRange = Array.apply(null, Array(5)).map(function (_, i) { return i; });

Embrace old and gold and give dinosaurs a chance!

Customizing to serve you better

Extend the Array's realm

Let's hitch a ride on the Array prototype for our range needs!

Array.range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => i + start);

Generating a range is as simple as on demand magic: Array.range(1, 5)

Performance obsession? Check!

Let's eke out every ounce of performance we can. Efficient loops can save the universe!

Argument uniformity

When crafting utility tools, ensure consistent argument handling. Negative step values or the start being greater than end - they shouldn't scare you!