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

🌐
GeeksforGeeks
geeksforgeeks.org › python › javascript-equivalent-to-python-s-range-function
JavaScript Equivalent to Python's range() Function - GeeksforGeeks
July 23, 2025 - In Python, the range() function is commonly used to generate a sequence of numbers. But in JavaScript, there is no direct equivalent to Python's range().
Discussions

Low Effort, High Reward - General Discussion - Heroes of the Storm Forums
Hero design and many of the reworks in recent years has been pretty good over all but there are some really severe outliers that need to be addressed. This doesn’t necessarily mean they’re overpowered, but are guilty of the crime of being low effort and yielding high rewards. More on us.forums.blizzard.com
🌐 us.forums.blizzard.com
1
April 6, 2026
JavaScript function similar to Python range() - Stack Overflow
Is there a function in JavaScript similar to Python's range()? I think there should be a better way than to write the following lines every time: array = new Array(); for (i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
Javascript equivalent of Python's range function? Requesting critique.
Its better to handle default arguments using a short circuit 'or' operator. if step is a falsy value it will get assigned to 1. step = step || 1; Don't mess around with 'arguments' , especially if you already have named parameters. find a way to let your function throw if I pass in range("Steak", "Salad"). Additionally, messing with arguments means JS engines like v8 can't optimize your function. do .. while is kind of a black sheep in JavaScript, no one really uses them. That doesn't mean you can't use them. Your function is returning [1, ..., 10] for range(1, 10). The upper bound should be excluded (you have an off by one error. Pythons range is implemented as an iterator/generator. that is you have an object with a state and a 'next' method. You can write a simple generator and iterator in JavaScript without the syntax for them in ES6. If you are seeking to duplicate python's range API/functionality, I think you should also duplicate its implementation. EDIT. Theres another error in the design that is more subtle, but perhaps more important than anything else. when I use this function, I would expect it to return an Array[Number]. In the part where you check for NaNs, you return a string on an invalid argument instead of throwing. The problem with this is it that your function now secretly has an additional return type of String. If this function is getting used somewhere inside another function, this may not even cause an error right away, instead it will spread and produce unintuitive effects that are hard to debug. consider: function example(a, b) { var r = range(a, b, 2); return r[0] + 2 + r[1] + 1; } // suppose there is a mistake and "a" gets passed into example, by another function or api example(2, "a"); => "i2n1" More on reddit.com
🌐 r/learnjavascript
9
3
November 29, 2015
making a range function in javascript - Stack Overflow
I am trying to make a function in javascript that returns an array from range(start,end) and im supposed to make an optional argument that defaults to one when it is undefined. I can get the functi... More on stackoverflow.com
🌐 stackoverflow.com
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Range
Range - Web APIs | MDN
Returns a Range object with the global Document as its start and end.
🌐
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 - The .from() method is a static method of the Array object in JavaScript ES6. 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...
🌐
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 - function* range(from, to, value) { while(from < to) { yield value ? value(from) : from; from++; } } [...range(64, 75, String.fromCharCode)] // ['@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] Cheers! JavaScript · Lifehacks · Range · Iterators · Generators ·
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
July 28, 2026 - In practice, such object is expected to actually have a length property and to have indexed elements in the range 0 to length - 1. (If it doesn't have all indices, it will be functionally equivalent to a sparse array.) Any integer index less than zero or greater than length - 1 is ignored when an array method operates on an array-like object.
Find elsewhere
🌐
Josh W. Comeau
joshwcomeau.com › snippets › javascript › range
Generate a "range" array in JavaScript • Josh W. Comeau
Feel free to use lodash’s range function if you prefer! This utility can be used in several ways. 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).
🌐
Math.js
mathjs.org › docs › reference › functions › range.html
Function range
math.range(str [, includeEnd]) // Create a range from a string, // where the string contains the // start, optional step, and end, // separated by a colon. math.range(start, end [, includeEnd]) // Create a range with start and // end and a step size of 1.
🌐
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 ...
🌐
GitHub
gist.github.com › 8d53b062dd17fa63992ea13bb44e9728
Range in JavaScript (Sequence generator) · GitHub
Range in JavaScript (Sequence generator). GitHub Gist: instantly share code, notes, and snippets.
🌐
Go Make Things
gomakethings.com › snippets › helpers › range
range.js | Go Make Things
January 24, 2018 - /** * Create a range of numbers ... {Number} max The last number in the range * @return {Array} The range */ function range (min, max) { // If only one number is provided, start at one if (max === undefined) { max = min; min ...
🌐
Blizzard
us.forums.blizzard.com › general discussion
Low Effort, High Reward - General Discussion - Heroes of the Storm Forums
April 6, 2026 - Hero design and many of the reworks in recent years has been pretty good over all but there are some really severe outliers that need to be addressed. This doesn’t necessarily mean they’re overpowered, but are guilty of the crime of being low effort and yielding high rewards.
🌐
Vogue
vogue.com › culture › sex & relationships › i want what they have: dakota johnson and role model
Dakota Johnson and Role Model Are My New Favorite Celebrity Relationship | Vogue
April 6, 2026 - I’ll be honest—when I first heard that Dakota Johnson and Role Model were dating, I felt like I was being given a cognitive function test.
Top answer
1 of 16
223

For a very simple range in ES6:

let range = n => Array.from(Array(n).keys())

From bigOmega's comment, this can be shortened using Spread syntax:

let range = n => [...Array(n).keys()]
2 of 16
138

No, there is none, but you can make one.

JavaScript's implementation of Python's range()

Trying to emulate how it works in Python, I would create function similar to this:

function range(start, stop, step) {
    if (typeof stop == 'undefined') {
        // one param defined
        stop = start;
        start = 0;
    }

    if (typeof step == 'undefined') {
        step = 1;
    }

    if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
        return [];
    }

    var result = [];
    for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
        result.push(i);
    }

    return result;
};

See this jsfiddle for a proof.

Comparison between range() in JavaScript and Python

It works in the following way:

  • range(4) returns [0, 1, 2, 3],
  • range(3,6) returns [3, 4, 5],
  • range(0,10,2) returns [0, 2, 4, 6, 8],
  • range(10,0,-1) returns [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
  • range(8,2,-2) returns [8, 6, 4],
  • range(8,2) returns [],
  • range(8,2,2) returns [],
  • range(1,5,-1) returns [],
  • range(1,5,-2) returns [],

and its Python counterpart works exactly the same way (at least in the mentioned cases):

>>> range(4)
[0, 1, 2, 3]
>>> range(3,6)
[3, 4, 5]
>>> range(0,10,2)
[0, 2, 4, 6, 8]
>>> range(10,0,-1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> range(8,2,-2)
[8, 6, 4]
>>> range(8,2)
[]
>>> range(8,2,2)
[]
>>> range(1,5,-1)
[]
>>> range(1,5,-2)
[]

So if you need a function to work similarly to Python's range(), you can use above mentioned solution.

🌐
Reddit
reddit.com › r/learnjavascript › javascript equivalent of python's range function? requesting critique.
r/learnjavascript on Reddit: Javascript equivalent of Python's range function? Requesting critique.
November 29, 2015 -

This is my implementation for Python's range function. I am trying to better my javascript skills and would like to know all the things I could fix.

function range(start, end, step) {
    var i, arr = [],
        step = typeof step !== 'undefined' ? step : 1;

    for (i = 0; i < arguments.length; i++) {
        if (isNaN(arguments[i]))
            return "invalid arguments"
    }

    if (arguments.length === 0)
        return 0;
    if (arguments.length === 1)
        return arguments[0];

    if (typeof end === 'undefined') {
        end = start;
        start = 0;
    }

    if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
        return [];
    }

    do {
        arr.push(start);
        start += step;
    } while (step > 0 ? start <= end : end <= start);

    return arr;
}
Top answer
1 of 3
2
Its better to handle default arguments using a short circuit 'or' operator. if step is a falsy value it will get assigned to 1. step = step || 1; Don't mess around with 'arguments' , especially if you already have named parameters. find a way to let your function throw if I pass in range("Steak", "Salad"). Additionally, messing with arguments means JS engines like v8 can't optimize your function. do .. while is kind of a black sheep in JavaScript, no one really uses them. That doesn't mean you can't use them. Your function is returning [1, ..., 10] for range(1, 10). The upper bound should be excluded (you have an off by one error. Pythons range is implemented as an iterator/generator. that is you have an object with a state and a 'next' method. You can write a simple generator and iterator in JavaScript without the syntax for them in ES6. If you are seeking to duplicate python's range API/functionality, I think you should also duplicate its implementation. EDIT. Theres another error in the design that is more subtle, but perhaps more important than anything else. when I use this function, I would expect it to return an Array[Number]. In the part where you check for NaNs, you return a string on an invalid argument instead of throwing. The problem with this is it that your function now secretly has an additional return type of String. If this function is getting used somewhere inside another function, this may not even cause an error right away, instead it will spread and produce unintuitive effects that are hard to debug. consider: function example(a, b) { var r = range(a, b, 2); return r[0] + 2 + r[1] + 1; } // suppose there is a mistake and "a" gets passed into example, by another function or api example(2, "a"); => "i2n1"
2 of 3
1
Start from unit testing your function. You will find that there is something wrong and how to fix it.
🌐
W3Schools
w3schools.com › python › ref_func_range.asp
Python range() Function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
Top answer
1 of 9
6

A very simple unidirectional (ascending), inclusive range – goes from x to y incrementing by 1 each time.

// range :: (Int, Int) -> [Int]
const range = (x,y) =>
  x > y ? [] : [x, ...range(x + 1, y)];

console.log(range(1,4)); // [1,2,3,4]
console.log(range(3,3)); // [3]
console.log(range(6,3)); // []
Run code snippetEdit code snippet Hide Results Copy to answer Expand

A slight adaptation that supports bidirectional (ascending or descending) range – still increments or decrements by 1

// range :: (Int, Int) -> [Int]
const range = (x,y) => {
  if (x > y)
    return range(y,x).reverse();
  else
    return x === y ? [y] : [x, ...range(x + 1, y)];
}

console.log(range(1,4)); // [1,2,3,4]
console.log(range(3,3)); // [3]
console.log(range(6,3)); // [6,5,4,3]
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Another adaptation that uses higher-order functions for more control over the range – this effectively gives you the stepping/incrementing behaviour some of you are looking for – tho this is more powerful because it lets you use a function, t, to choose the next value.

const gte = x => y => y >= x;
const lte = x => y => y <= x;
const add = x => y => y + x;
const sub = x => y => y - x;

// range :: (Int, (Int -> Bool), (Int -> Int)) -> [Int]
const range = (x, p, t) => {
  if (p(x))
    return [x, ...range(t(x), p, t)];
  else
    return [];
};

console.log(range(2, lte(8), add(2))); // [2,4,6,8]
console.log(range(9, gte(0), sub(3))); // [9,6,3,0]
console.log(range(9, gte(0), sub(5))); // [9, 4]

// very power. wow.
const double = x => x + x;
console.log(range(2, lte(50), double)); // [2,4,8,16,32]
Run code snippetEdit code snippet Hide Results Copy to answer Expand

This function has the same risks inherent with for and while – it's up to you to make sure you don't put it into an infinite loop.


functional overload

Warning: Esoteric, impractical functionals ahead. The following information is provided for your academic pleasure only.

The range function also happens to be one of my favourite demonstrations of the Y combinator. I'll show you two examples here.

naïve range

const U = f => f (f);
const Y = U (h => f => f (x => h (h) (f) (x)));

const range = Y (f => acc => x => y =>
  x > y ? acc : f ([...acc, x]) (x + 1) (y)
) ([]);

console.log(range (3) (6)); // [3,4,5,6]
console.log(range (6) (6)); // [6]
console.log(range (9) (6)); // []
Run code snippetEdit code snippet Hide Results Copy to answer Expand

and the higher-order range

const U = f => f (f);
const Y = U (h => f => f (x => h (h) (f) (x)));

const lt = x => y => y < x;
const gt = x => y => y > x;
const add1 = x => x + 1;
const sub1 = x => x - 1;

const range = Y (f => acc => x => p => t =>
  p(x) ? f ([...acc, x]) (t(x)) (p) (t) : acc 
) ([]);

console.log(range (3) (lt(6)) (add1)); // [3,4,5]
console.log(range (6) (lt(6)) (add1)); // []
console.log(range (9) (gt(6)) (sub1)); // [9,8,7]
Run code snippetEdit code snippet Hide Results Copy to answer Expand

What a thing of beauty that is.

2 of 9
5

You could simplify the code a bit and use the increment variable for incrementing. But before, I suggest to test if the value is falsy (0, null, undefined, etc) and assign then 1 to it.

Not implemented: check if start and end is appropriate.

function range(start, end, increment) {
    var array = [];
    var current = start;

    increment = increment || 1;
    if (increment > 0) {
        while (current <= end) {
            array.push(current);
            current += increment;
        }
    } else {
        while (current >= end) {
            array.push(current);
            current += increment;
        }
    }
    return array;
}

console.log(range(1, 3, 0));    
console.log(range(2, 5));
console.log(range(1, 9, 1));
console.log(range(5, 2, -1));    
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
allow_nan (bool) – If False, serialization of out-of-range float values (nan, inf, -inf) will result in a ValueError, in strict compliance with the JSON specification. If True (the default), their JavaScript equivalents (NaN, Infinity, -Infinity) are used.
🌐
Reddit
reddit.com › r/javascript › a quick look into `number.range();` stage-1 proposal
r/javascript on Reddit: A quick look into `Number.range();` Stage-1 proposal
July 19, 2020 - Number.range() proposal for ECMAScript in currently on stage-1 and if it makes to stage-4(I strongly... Tagged with javascript. ... Probably wouldn't use it exactly like that, but imagine creating Number.range(0, Infinity) and then passing it off to other functions, which can then take() at-will.
🌐
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 - range is a function that basically takes in a starting index and ending index then return a list of all integers from start to end.