Numbers

[...Array(5).keys()];
 => [0, 1, 2, 3, 4]

Character iteration

String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
 => "ABCD"

Iteration

for (const x of Array(5).keys()) {
  console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
 => 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"

As functions

function range(size, startAt = 0) {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar, endChar) {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}

As typed functions

function range(size:number, startAt:number = 0):ReadonlyArray<number> {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}

lodash.js _.range() function

_.range(10);
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
 => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
 => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
 => "ABCD"

Old non es6 browsers without a library:

Array.apply(null, Array(5)).map(function (_, i) {return i;});
 => [0, 1, 2, 3, 4]

console.log([...Array(5).keys()]);

(ES6 credit to nils petersohn and other commenters)

Answer from Fuji on Stack Overflow
Top answer
1 of 16
2798

Numbers

[...Array(5).keys()];
 => [0, 1, 2, 3, 4]

Character iteration

String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
 => "ABCD"

Iteration

for (const x of Array(5).keys()) {
  console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
 => 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"

As functions

function range(size, startAt = 0) {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar, endChar) {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}

As typed functions

function range(size:number, startAt:number = 0):ReadonlyArray<number> {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}

lodash.js _.range() function

_.range(10);
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
 => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
 => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
 => "ABCD"

Old non es6 browsers without a library:

Array.apply(null, Array(5)).map(function (_, i) {return i;});
 => [0, 1, 2, 3, 4]

console.log([...Array(5).keys()]);

(ES6 credit to nils petersohn and other commenters)

2 of 16
654

For numbers you can use ES6 Array.from(), which works in everything these days except IE:

Shorter version:

Array.from({length: 20}, (x, i) => i);

Longer version:

Array.from(new Array(20), (x, i) => i);​​​​​​

which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:

Array.from(Array(20).keys());
// or
[...Array(20).keys()];

Lower and upper bounds can be specified too, for example:

Array.from(new Array(20), (x, i) => i + *lowerBound*);

An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

🌐
freeCodeCamp
freecodecamp.org › news › javascript-range-create-an-array-of-numbers-with-the-from-method
JavaScript Range – How to Create an Array of Numbers with .from() in JS ES6
November 7, 2024 - It creates a new, shallow-copied Array instance from an array-like or iterable object like map and set. This method returns an array from any object with a length property. You can use it to create an Array of numbers within a specified range.
🌐
Josh W. Comeau
joshwcomeau.com › snippets › javascript › range
Generate a "range" array in JavaScript • Josh W. Comeau
You can pass a single number, to generate a range from 0 through that number: ... You'll notice that the array produced is inclusive of the starting number, but exclusive of the ending number. range(10, 20) includes 10, but does not include 20. This is done intentionally, to match the behaviour of JavaScript methods like slice(opens in new tab).
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-select-a-range-from-an-array-in-javascript-96a163fe8f34
How to Select a Range from an Array in JavaScript | by Dr. Derek Austin 🥳 | JavaScript in Plain English
January 5, 2023 - It may be no surprise, then, that I wish I could use Ruby’s range syntax to select a range inside an array — it’s just so convenient! In Ruby, ["🏄","🏊","🌴","🍹","🌞"][2..3] equals ["🌴","🍹"]. In JavaScript, we need to use Array.prototype.slice(). Here’s how. “The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › initialize array with range
Initialize a JavaScript array with a given numeric range - 30 seconds of code
December 25, 2023 - Let's dive into building a JavaScript equivalent. ... All methods presented here will produce an array containing start (inclusive) but not end (exclusive) for consistency with Python's range() method. To include the end value, you will have to alter the length formula and the mapping function accordingly. We can use Array.from() for the purpose of creating a new array.
🌐
Jason Watmore's Blog
jasonwatmore.com › post › 2021 › 10 › 02 › vanilla-js-create-an-array-with-a-range-of-numbers-in-a-javascript
Vanilla JS - Create an array with a range of numbers in a JavaScript | Jason Watmore's Blog
October 2, 2021 - (function() { // 0 to 9 const range = [...Array(10).keys()]; document.getElementById('rangeOne').innerHTML = JSON.stringify(range); })(); (function() { // 1 to 10 const start = 1; const end = 10; const range = [...Array(end - start + 1).keys()].map(x => x + start); document.getElementById('rangeTwo').innerHTML = JSON.stringify(range); })(); (function() { // 5 to 20 const start = 5; const end = 20; const range = [...Array(end - start + 1).keys()].map(x => x + start); document.getElementById('rangeThree').innerHTML = JSON.stringify(range); })(); (function() { // 0 to 100 step 10 const start = 0;
🌐
DEV Community
dev.to › ycmjason › how-to-create-range-in-javascript-539i
JavaScript Range: How to create range in Javascript - DEV Community
April 8, 2020 - As array from works with arrayLike structures and receives a second optional argument mapFn, it's a nice candidate to build range.
Find elsewhere
🌐
QuickRef.ME
quickref.me › home › how to create an array of numbers in the given range in javascript - quickref.me
How to create an array of numbers in the given range in JavaScript - QuickRef.ME
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function. Let's define this short function: const range = (min, max) => [...Array(max - min + 1).keys()].map(i => i + min); const range = (min, max) => Array(max - min + 1).fill(0).map((_, i) => min + i); const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i); range(5, 10); // [5, 6, 7, 8, 9, 10] More ·
🌐
Kieran Barker
barker.codes › blog › create-a-range-of-numbers-using-the-array-from-method
Create a range of numbers using the Array.from() method - Kieran Barker
October 31, 2022 - JavaScript doesn't have a range function, but you can create a range of numbers using the Array.from() method.
🌐
DEV Community
dev.to › asyraf › how-to-get-values-from-array-with-specific-range-in-javascript-56a7
How to Get Values From Array With Specific Range in Javascript - DEV Community
July 1, 2021 - However, since I am not using Ruby on this project and am using vanilla Javascript, I wonder how to achieve the same result. Turns out that it's extremely easy to do !!! var myArray = ['a','b','c','d','e','f','g', 'h','i']; var sliced = myArray.slice(0, 5); //will contain ['a', 'b', 'c','d', 'e'] Easy right. If you notice, the last index is different from the Ruby implementation.
🌐
Go Make Things
gomakethings.com › how-to-create-a-range-of-numbers-with-vanilla-js
How to create a range of numbers with vanilla JS | Go Make Things
January 13, 2021 - Following Darren’s original code, we subtract the min from the max, then add 1, to get the length of the array. var range = function (min, max) { // Create a ranged array return Array.from(new Array(max - min + 1).keys()); };
🌐
DEV Community
dev.to › domhabersack › create-number-ranges-in-javascript-5494
🔥 Create number ranges in JavaScript - DEV Community
December 19, 2020 - const range = [...Array(5).keys()] // ⇒ [0, 1, 2, 3, 4] // the number in `Array(number)` describes how many values you want [...Array(7).keys()] // ⇒ [0, 1, 2, 3, 4, 5, 6] // you can `map` the values to shift or otherwise manipulate the range [...Array(4).keys()].map(n => n + 3) // ⇒ [3, 4, 5, 6] [...Array(4).keys()].map(n => n - 3) // ⇒ [-3, -2, -1, 0] [...Array(4).keys()].map(n => n * 2) // ⇒ [0, 2, 4, 6]
🌐
YouTube
youtube.com › watch
Array From in Javascript - Writing Range Function - YouTube
🧠 1-on-1 Frontend Mentorship (90-min paid session) → https://monsterlessons-academy.com/mentorship?utm_source=youtube&utm_medium=description_link🎁 Free PDF
Published: July 8, 2023
🌐
YouTube
youtube.com › shorts › MhTFPI8rgK8
Learn To Make a Range Function In Under a Minute - JavaScript Array.from - YouTube
In this video, we'll learn how to create a range function with the Javascript Array.from method. This range function will allow us to create bounds on our Ar...
Published: January 23, 2023
🌐
Medium
medium.com › swlh › creating-a-range-in-javascript-e2303e05979b
Creating a Range in JavaScript. Have you ever worked on a problem where… | by Anna M Dybas | The Startup | Medium
September 3, 2020 - I was surprised to find that there is nothing similar to the simple built in Ruby Range method, and quite a bit of different ways to accomplish this in JavaScript. In Ruby, you can build a new array from ranges by using the built in method .to_a or the Array method.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-an-array-containing-1-n-numbers-in-javascript
JavaScript - Create an Array Containing 1...N Numbers - GeeksforGeeks
December 31, 2024 - JavaScript · // Requiring the lodash library const _ = require("lodash"); let range_arr = _.range(1,5); console.log(range_arr); Output: [ 1, 2, 3, 4 ] In this example : _.range(1, 5): Creates an array starting at 1 and ending before 5. The resulting array is [1, 2, 3, 4]. A generator function generateNumbers(N) yields numbers from 1 to N.
🌐
Will Vincent
wsvincent.com › javascript-array-range-function
JavaScript Range Array Function | Will Vincent
November 2, 2017 - function range(start, edge, step) { // If only 1 number passed make it the edge and 0 the start if (arguments.length === 1) { edge = start; start = 0; } // Validate edge/start edge = edge || 0; step = step || 1; // Create array of numbers, stopping ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › from
Array.from() - JavaScript - MDN Web Docs
Python, Clojure, etc.) const range = (start, stop, step) => Array.from( { length: Math.ceil((stop - start) / step) }, (_, i) => start + i * step, ); // Generate a sequence of numbers from 0 (inclusive) to 5 (exclusive), incrementing by 1 range(0, 5, 1); // [0, 1, 2, 3, 4] // Generate a sequence of numbers from 1 (inclusive) to 10 (exclusive), incrementing by 2 range(1, 10, 2); // [1, 3, 5, 7, 9] // Generate the Latin alphabet making use of it being ordered as a sequence range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) => String.fromCharCode(x), ); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] The from() method can be called on any constructor function that accepts a single argument representing the length of the new array.
🌐
Medium
artemee-lemann.medium.com › range-function-in-javascript-b12fbff42d03
range() function in JavaScript. How many times have to been doing… | by Artemee Lemann | Medium
December 1, 2023 - Let’s see how to create arrays of values of a given range: const arr = [...range(10, 20)] // [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] We can also handle some cases to normalize the input values if they were passed in wrong order · // Set increment/decrement function* range(from, to) { const step = from <= to ?