In ES6 using Array from() and keys() methods.

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Shorter version using spread operator.

[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Start from 1 by passing map function to Array from(), with an object with a length property:

Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Answer from Niko Ruotsalainen on Stack Overflow
Top answer
1 of 16
3985

In ES6 using Array from() and keys() methods.

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Shorter version using spread operator.

[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Start from 1 by passing map function to Array from(), with an object with a length property:

Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2 of 16
901

You can do so:

var N = 10; 
Array.apply(null, {length: N}).map(Number.call, Number)

result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

or with random values:

Array.apply(null, {length: N}).map(Function.call, Math.random)

result: [0.7082694901619107, 0.9572225909214467, 0.8586748542729765, 0.8653848143294454, 0.008339877473190427, 0.9911756622605026, 0.8133423360995948, 0.8377588465809822, 0.5577575915958732, 0.16363654541783035]

Explanation

First, note that Number.call(undefined, N) is equivalent to Number(N), which just returns N. We'll use that fact later.

Array.apply(null, [undefined, undefined, undefined]) is equivalent to Array(undefined, undefined, undefined), which produces a three-element array and assigns undefined to each element.

How can you generalize that to N elements? Consider how Array() works, which goes something like this:

function Array() {
    if ( arguments.length == 1 &&
         'number' === typeof arguments[0] &&
         arguments[0] >= 0 && arguments &&
         arguments[0] < 1 << 32 ) {
        return [ … ];  // array of length arguments[0], generated by native code
    }
    var a = [];
    for (var i = 0; i < arguments.length; i++) {
        a.push(arguments[i]);
    }
    return a;
}

Since ECMAScript 5, Function.prototype.apply(thisArg, argsArray) also accepts a duck-typed array-like object as its second parameter. If we invoke Array.apply(null, { length: N }), then it will execute

function Array() {
    var a = [];
    for (var i = 0; i < /* arguments.length = */ N; i++) {
        a.push(/* arguments[i] = */ undefined);
    }
    return a;
}

Now we have an N-element array, with each element set to undefined. When we call .map(callback, thisArg) on it, each element will be set to the result of callback.call(thisArg, element, index, array). Therefore, [undefined, undefined, …, undefined].map(Number.call, Number) would map each element to (Number.call).call(Number, undefined, index, array), which is the same as Number.call(undefined, index, array), which, as we observed earlier, evaluates to index. That completes the array whose elements are the same as their index.

Why go through the trouble of Array.apply(null, {length: N}) instead of just Array(N)? After all, both expressions would result an an N-element array of undefined elements. The difference is that in the former expression, each element is explicitly set to undefined, whereas in the latter, each element was never set. According to the documentation of .map():

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Therefore, Array(N) is insufficient; Array(N).map(Number.call, Number) would result in an uninitialized array of length N.

Compatibility

Since this technique relies on behaviour of Function.prototype.apply() specified in ECMAScript 5, it will not work in pre-ECMAScript 5 browsers such as Chrome 14 and Internet Explorer 9.

🌐
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).
🌐
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 - The below examples include creating ... to twenty ([5, 6, 7, ..., 20]), and an array with the range zero to one hundred with a step size of ten ([0, 10, 20, ..., 100])....
🌐
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 - In this article, you will learn what the .from() static method is all about, how it works, and how you can create a range of numbers in JavaScript. In case you are in a rush, here is a method to help you get the range: const arrayRange = (start, stop, step) => Array.from( { length: (stop - start) / step + 1 }, (value, index) => start + index * step ); console.log(arrayRange(1, 5, 1)); // [1,2,3,4,5]
🌐
Java2Blog
java2blog.com › home › javascript › create array from 1 to 100 in javascript
Create Array from 1 to 100 in JavaScript [6 Ways] - Java2Blog
December 27, 2022 - Use a for loop that will iterate over a variable whose value starts from 1 and ends at 100 while the variable’s value is incremented by 1 in each iteration. Inside the for loop, use the push() method to insert a value to an array.
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

🌐
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 - I cook delicious TypeScript / JavaScript nuggets. 🍳 ... This is why { length } count as an "array-like" object. You could write in the long form: { length: 3, 0: undefined, 1: undefined, 2: undefined, } But it's not worth listing those entries out coz they are by default undefined anyways. ... Yes, excellent solution. This, slimmed down, version also works... const range = (start, end, length = end - start) => Array.from({ length }, (_, i) => start + i)
Find elsewhere
🌐
W3Schools
w3schools.com › js › js_random.asp
JavaScript Random
// Returns a random integer from 1 to 100 (both included): Math.floor(Math.random() * 100) + 1; Try it Yourself » · As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer ...
🌐
DEV Community
dev.to › domhabersack › create-number-ranges-in-javascript-5494
🔥 Create number ranges in JavaScript - DEV Community
December 19, 2020 - To get a range of numbers in JavaScript, initialize an array by spreading the keys of another array into it. You can shift the range up or down, or do things like have it contain only even numbers. const range = [...Array(5).keys()] // ⇒ [0, ...
🌐
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 - var range = function (min, max) { // If only one number is provided, start at one if (max === undefined) { max = min; min = 1; } // Create a ranged array return Array.from(new Array(max - min + 1).keys()).map(function (num) { return num + min; }); };
🌐
Codecademy
codecademy.com › forum_questions › 51c858349c4e9dd24201011d
Print all prime number between 1 to 100 by javascript | Codecademy
This causes quite a few problems considering that I program javascript without a debugger and use my browser to compile it via HTML. This method is probably one of the most reliable and can be applied to any size of numbers but can get very inefficient. ... //Sets up the counter (1-100 right now) for (var counter = 1; counter <= 100; counter++) //Creates a variable called not_prime and automatically sets it to false for each of the counter numbers { var not_prime = false; //Creates a for loop with a variable called div.
🌐
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 - // Set increment/decrement function* range(from, to) { const step = from <= to ? 1 : -1; while(from < to) { yield from; from += step; } } // Flip values function* range(from, to) { if (from > to) [from, to] = [to, from]; while(from < to) yield from++ }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › random
Math.random() - JavaScript - MDN Web Docs - Mozilla
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random ...
🌐
Our Code World
ourcodeworld.com › articles › read › 1486 › how-to-print-the-numbers-from-1-to-100-without-including-numbers-in-your-javascript-code
How to print the numbers from 1 to 100 without including numbers in your JavaScript code | Our Code World
April 16, 2021 - If instead of 0, you need to start from 1, simply use the length of a string with a dot as the start point: let max = "..........".length; for(let i = ".".length;i <= (max * max);i++){ console.log(i); } If the range that you need to print is ...
🌐
SheCodes
shecodes.io › athena › 11677-how-to-generate-a-random-integer-between-the-numbers-1-100-in-javascript
[JavaScript] - How to Generate a Random Integer Between the Numbers 1-100 in JavaScript
See what students from United States are saying 250,000+ students recommend See reviews ... Learn how to generate a random integer between 1 and 100, inclusive, in JavaScript using the Math.random() and Math.floor() methods.
🌐
Medium
medium.com › @ryan_forrester_ › random-number-in-a-range-in-javascript-464dfeddf8d4
Random Number in a Range in JavaScript | by ryan | Medium
September 11, 2024 - This guide will provide you with ... provides a built-in method, Math.random(), which generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive)....
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Use Recursion to Create a Range of Numbers - JavaScript - The freeCodeCamp Forum
March 31, 2023 - Hello, I’ve just completed the Basic JavaScript portion of the JavaScript curriculum. I completed the few recursion lessons without the hints, but they’re pretty simple, considering they’re nearly identical to the exam…
🌐
Quora
quora.com › How-do-I-get-a-random-number-from-1-to-100-in-JavaScript
How to get a random number from 1 to 100 in JavaScript - Quora
Answer (1 of 4): Use “Math.random()”. Syntax: [code]Math.random(); [/code]Return Value: This method returns a random number between 0 (inclusive) and 1 (exclusive). But to get a random number from 1 to 100, [code]Math.floor(Math.random() * 100) + 1; //returns a random integer from 1 to 100 ...