1650

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")

That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?

10
  • 2
    Prototype.js has the $R function, but other than that I don't really think so.
    – Yi Jiang
    Oct 9, 2010 at 2:42
  • This (related) question has some excellent answers: stackoverflow.com/questions/6299500/…
    – btk
    Feb 25, 2015 at 14:47
  • 2
    When lover bound is zero this oneliner: Array.apply(null, { length: 10 }).map(eval.call, Number)
    – csharpfolk
    Jul 25, 2016 at 16:32
  • 1
    Possible duplicate of Create a JavaScript array containing 1...N
    – KyleMit
    Mar 28, 2019 at 20:08
  • 1
    No, but you can define the function using: const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); (see 'Sequence generator (range)' from MSDN) NOTE: This function only works if all parameters are specified (ie. range(1,5,1) produces the array [1,2,3,4,5], but range(1,5) produces an empty array)
    – Dave F
    Feb 15, 2021 at 8:12

92 Answers 92

2648

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)

22
  • 95
    Because if it's useful anywhere it is probably useful in JS. (JS can do functional programming type stuff, which can benefit from a range(0 statement. That and a thousand other reasons it might be useful in some semirare case)
    – Lodewijk
    May 18, 2013 at 19:47
  • 6
    Any idea why simply using (new Array(5)).map(function (value, index) { return index; }) wouldn't work? This returns [undefined × 5] for me in Chrome DevTools.
    – Lewis
    Dec 15, 2015 at 21:52
  • 13
    @Lewis Because an array defined with that has empty slots that won't be iterated over with map() or one of its friends.
    – alex
    Dec 15, 2015 at 23:09
  • 30
    Array(5).fill() is also mappable Mar 21, 2017 at 12:54
  • 10
    Array.from(Array(5).keys()) is an ES6 alternative that works in typescript without the downlevelIteration compiler flag if anyone was looking Oct 17, 2017 at 13:30
604

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

9
  • 78
    The first example can even be simplified to [...Array(20).keys()]
    – Delapouite
    Nov 20, 2015 at 17:39
  • 51
    Slightly more succinct than the Array.from() method, and faster than both: Array(20).fill().map((_, i) => i)
    – Stu Cox
    Feb 20, 2016 at 8:34
  • 11
    @Delapouite @jib And this as well: Array.from({length: end - start}, (v, k) => k + start) May 15, 2016 at 7:11
  • Nifty if you'd like to create array of empty subarrays too (var matrix = Array.from(new Array(3), () => []);). Nov 16, 2016 at 11:25
  • 2
    @icc97 Yes, linters may complain, although in JavaScript omitting a function argument defined to be the same as passing undefined, so fill() (with no argument) isn’t wrong per se. The fill value isn’t used in that solution, so if you like you could use fill(0) to save a few characters.
    – Stu Cox
    Jan 16, 2019 at 8:17
260

My new favorite form (ES2015)

Array(10).fill(1).map((x, y) => x + y)

And if you need a function with a step param:

const range = (start, stop, step = 1) =>
  Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)

Another possible implementation suggested by the MDN docs:

// Sequence generator function 
// (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => 
  Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step))
5
  • 3
    The argument you pass into Array(Math.ceil((stop - start) / step) + 1), needs the +1 at the end, to really mimic php's "inclusive" behaviour. Oct 26, 2018 at 8:16
  • Try this: Array(10).fill(1).map((x, i) => i) Jan 25, 2019 at 1:30
  • 1
    I fixed @rodfersou's code so that stop means the end position: let range = (start, stop, step=1) => Array(stop - start + 1).fill(start).map((x, y) => x + y * step)
    – ximo
    Nov 26, 2019 at 23:46
  • 1
    FYI MDN recommends a range function like the second example here: const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
    – Jacktose
    Feb 3, 2022 at 21:19
  • 1
    It is simply incredible that a language as high-level and popular as JS still lacks a straightforward range or [:] syntax in 2023. I can fathom no reason for it other than layers upon layers of bureaucratic red tape. Perhaps someone should pressure the ES committee to add such a feature? Some nice new languages, such as Rust, have no problem adding syntactic sugar when it would help, even despite those languages being much more systematic and "closer to the bare metal" than JS.
    – Asker
    Aug 17 at 16:29
111

Here's my 2 cents:

function range(start, end) {
  return Array.apply(0, Array(end - 1))
    .map((element, index) => index + start);
}
3
  • 12
    This is actually wrong because the question is asking for start & end values. Not start & count/distance. Mar 31, 2018 at 6:52
  • 3
    This answer does not work as expected. The output is not usable. Jun 3, 2021 at 12:47
  • it would work as expected, when Array(end - 1) is changed like Array(end - start + 1)
    – qba-dev
    Apr 21, 2022 at 7:15
85

It works for characters and numbers, going forwards or backwards with an optional step.

var range = function(start, end, step) {
    var range = [];
    var typeofStart = typeof start;
    var typeofEnd = typeof end;

    if (step === 0) {
        throw TypeError("Step cannot be zero.");
    }

    if (typeofStart == "undefined" || typeofEnd == "undefined") {
        throw TypeError("Must pass start and end arguments.");
    } else if (typeofStart != typeofEnd) {
        throw TypeError("Start and end arguments must be of same type.");
    }

    typeof step == "undefined" && (step = 1);

    if (end < start) {
        step = -step;
    }

    if (typeofStart == "number") {

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

    } else if (typeofStart == "string") {

        if (start.length != 1 || end.length != 1) {
            throw TypeError("Only strings with one character are supported.");
        }

        start = start.charCodeAt(0);
        end = end.charCodeAt(0);

        while (step > 0 ? end >= start : end <= start) {
            range.push(String.fromCharCode(start));
            start += step;
        }

    } else {
        throw TypeError("Only string and number types are supported");
    }

    return range;

}

jsFiddle.

If augmenting native types is your thing, then assign it to Array.range.

var range = function(start, end, step) {
    var range = [];
    var typeofStart = typeof start;
    var typeofEnd = typeof end;

    if (step === 0) {
        throw TypeError("Step cannot be zero.");
    }

    if (typeofStart == "undefined" || typeofEnd == "undefined") {
        throw TypeError("Must pass start and end arguments.");
    } else if (typeofStart != typeofEnd) {
        throw TypeError("Start and end arguments must be of same type.");
    }

    typeof step == "undefined" && (step = 1);

    if (end < start) {
        step = -step;
    }

    if (typeofStart == "number") {

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

    } else if (typeofStart == "string") {

        if (start.length != 1 || end.length != 1) {
            throw TypeError("Only strings with one character are supported.");
        }

        start = start.charCodeAt(0);
        end = end.charCodeAt(0);

        while (step > 0 ? end >= start : end <= start) {
            range.push(String.fromCharCode(start));
            start += step;
        }

    } else {
        throw TypeError("Only string and number types are supported");
    }

    return range;

}

console.log(range("A", "Z", 1));
console.log(range("Z", "A", 1));
console.log(range("A", "Z", 3));


console.log(range(0, 25, 1));

console.log(range(0, 25, 5));
console.log(range(20, 5, 5));

0
74

Simple range function:

function range(start, stop, step) {
    var a = [start], b = start;
    while (b < stop) {
        a.push(b += step || 1);
    }
    return a;
}

To incorporate the BigInt data type some check can be included, ensuring that all variables are same typeof start:

function range(start, stop, step) {
    var a = [start], b = start;
    if (typeof start == 'bigint') {
        stop = BigInt(stop)
        step = step? BigInt(step): 1n;
    } else
        step = step || 1;
    while (b < stop) {
        a.push(b += step);
    }
    return a;
}

To remove values higher than defined by stop e.g. range(0,5,2) will include 6, which shouldn't be.

function range(start, stop, step) {
    var a = [start], b = start;
    while (b < stop) {
        a.push(b += step || 1);
    }
    return (b > stop) ? a.slice(0,-1) : a;
}
3
  • 1
    This doesn't work when step != 1, the while condition needs to take step into account. My updated version with a default step value: function range(start, stop, step){ step = step || 1 var a=[start], b=start; while((b+step) < stop){ console.log("b: " + b + ". a: " + a + "."); b+=step; a.push(b); } return a; }
    – daveharris
    Oct 25, 2017 at 21:51
  • @daveharris I added a default step above, (step || 1). May 9, 2018 at 14:57
  • i have to say just by looking at it, if you try million records, it'll crash your computer. If not, just try with one more zero. I don't think you can exceed a number with more than 8 zeros.
    – windmaomao
    Dec 25, 2020 at 19:08
59

OK, in JavaScript we don't have a range() function like PHP, so we need to create the function which is quite easy thing, I write couple of one-line functions for you and separate them for Numbers and Alphabets as below:

for Numbers:

function numberRange (start, end) {
  return new Array(end - start).fill().map((d, i) => i + start);
}

and call it like:

numberRange(5, 10); //[5, 6, 7, 8, 9]

for Alphabets:

function alphabetRange (start, end) {
  return new Array(end.charCodeAt(0) - start.charCodeAt(0)).fill().map((d, i) => String.fromCharCode(i + start.charCodeAt(0)));
}

and call it like:

alphabetRange('c', 'h'); //["c", "d", "e", "f", "g"]
1
  • 5
    I think there are off-by-one errors in these functions. Should be Array(end - start + 1), and Array(end.charCodeAt(0) - start.charCodeAt(0) + 1).
    – Paul
    Apr 5, 2018 at 16:59
47
Array.range = function(a, b, step){
    var A = [];
    if(typeof a == 'number'){
        A[0] = a;
        step = step || 1;
        while(a+step <= b){
            A[A.length]= a+= step;
        }
    }
    else {
        var s = 'abcdefghijklmnopqrstuvwxyz';
        if(a === a.toUpperCase()){
            b = b.toUpperCase();
            s = s.toUpperCase();
        }
        s = s.substring(s.indexOf(a), s.indexOf(b)+ 1);
        A = s.split('');        
    }
    return A;
}
    
    
Array.range(0,10);
// [0,1,2,3,4,5,6,7,8,9,10]
    
Array.range(-100,100,20);
// [-100,-80,-60,-40,-20,0,20,40,60,80,100]
    
Array.range('A','F');
// ['A','B','C','D','E','F')
    
Array.range('m','r');
// ['m','n','o','p','q','r']
3
  • 5
    You really shouldn't jerry-rig methods onto the Array prototype.
    – moltarze
    Oct 8, 2019 at 22:01
  • This method only works with integers and characters. If the parameters are null, undefined, NaN, boolean, array, object, etc, this method returns the following error: undefined method toUpperCase to etc! Dec 4, 2019 at 6:53
  • As miike3459 wrote, if one day Array.range is added to standard lib you might have a serious problem.
    – row
    Nov 17, 2021 at 13:40
46

https://stackoverflow.com/a/49577331/8784402

With Delta/Step

smallest and one-liner
[...Array(N)].map((_, i) => from + i * step);

Examples and other alternatives

[...Array(10)].map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10)).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((_, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
Range Function
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

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

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

From-To with steps/delta

using iterators
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

For Typescript

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

https://stackoverflow.com/a/64599169/8784402

Generate Character List with one-liner

const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));

console.log("from A to G", charList('A', 'G'));
console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
console.log("reverse order from Z to P", charList('Z', 'P', -1));
console.log("from 0 to 5", charList('0', '5', 1));
console.log("from 9 to 5", charList('9', '5', -1));
console.log("from 0 to 8 with step 2", charList('0', '8', 2));
console.log("from α to ω", charList('α', 'ω'));
console.log("Hindi characters from क to ह", charList('क', 'ह'));
console.log("Russian characters from А to Я", charList('А', 'Я'));

For TypeScript
const charList = (p: string, q: string, d = 1) => {
  const a = p.charCodeAt(0),
    z = q.charCodeAt(0);
  return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
    String.fromCharCode(a + i * d)
  );
};
1
  • 1
    As an aside, it is incredible that a language as high-level and popular as JS still lacks a straightforward range or [:] syntax in 2023. I can fathom no reason for it other than layers upon layers of bureaucratic red tape. Someone should pressure the ES committee to add such a feature. Newer languages, such as Rust, have no problem adding syntactic sugar when it would help, even though those languages are much more systematic and "close to the bare metal" than JS.
    – Asker
    Aug 17 at 16:29
31
var range = (l,r) => new Array(r - l).fill().map((_,k) => k + l);
2
  • 2
    Very neat! Although, it's important to note it doesn't work on any IE or Opera. May 22, 2016 at 0:45
  • @RafaelXavier will work on IE with Array.fill() polyfill
    – mwag
    Oct 21, 2017 at 11:42
29

Handy function to do the trick, run the code snippet below

function range(start, end, step, offset) {
  
  var len = (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1;
  var direction = start < end ? 1 : -1;
  var startingPoint = start - (direction * (offset || 0));
  var stepSize = direction * (step || 1);
  
  return Array(len).fill(0).map(function(_, index) {
    return startingPoint + (stepSize * index);
  });
  
}

console.log('range(1, 5)=> ' + range(1, 5));
console.log('range(5, 1)=> ' + range(5, 1));
console.log('range(5, 5)=> ' + range(5, 5));
console.log('range(-5, 5)=> ' + range(-5, 5));
console.log('range(-10, 5, 5)=> ' + range(-10, 5, 5));
console.log('range(1, 5, 1, 2)=> ' + range(1, 5, 1, 2));

here is how to use it

range (Start, End, Step=1, Offset=0);

  • inclusive - forward range(5,10) // [5, 6, 7, 8, 9, 10]
  • inclusive - backward range(10,5) // [10, 9, 8, 7, 6, 5]
  • step - backward range(10,2,2) // [10, 8, 6, 4, 2]
  • exclusive - forward range(5,10,0,-1) // [6, 7, 8, 9] not 5,10 themselves
  • offset - expand range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
  • offset - shrink range(5,10,0,-2) // [7, 8]
  • step - expand range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]

hope you find it useful.


And here is how it works.

Basically I'm first calculating the length of the resulting array and create a zero filled array to that length, then fill it with the needed values

  • (step || 1) => And others like this means use the value of step and if it was not provided use 1 instead
  • We start by calculating the length of the result array using (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1) to put it simpler (difference* offset in both direction/step)
  • After getting the length, then we create an empty array with initialized values using new Array(length).fill(0); check here
  • Now we have an array [0,0,0,..] to the length we want. We map over it and return a new array with the values we need by using Array.map(function() {})
  • var direction = start < end ? 1 : 0; Obviously if start is not smaller than the end we need to move backward. I mean going from 0 to 5 or vice versa
  • On every iteration, startingPoint + stepSize * index will gives us the value we need
0
29

--- UPDATE (Thanks to @lokhmakov for simplification) ---

Another version using ES6 generators ( see great Paolo Moretti answer with ES6 generators ):

const RANGE = (x,y) => Array.from((function*(){
  while (x <= y) yield x++;
})());

console.log(RANGE(3,7));  // [ 3, 4, 5, 6, 7 ]

Or, if we only need iterable, then:

const RANGE_ITER = (x,y) => (function*(){
  while (x <= y) yield x++;
})();

for (let n of RANGE_ITER(3,7)){
  console.log(n);
}

// 3
// 4
// 5
// 6
// 7

--- ORGINAL code was: ---

const RANGE = (a,b) => Array.from((function*(x,y){
  while (x <= y) yield x++;
})(a,b));

and

const RANGE_ITER = (a,b) => (function*(x,y){
  while (x <= y) yield x++;
})(a,b);
0
26

If, on Visual Studio Code, you faced the error:

screenshot

Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

Instead of

[...Array(3).keys()]

you can rely on

Array.from(Array(3).keys())

More on downlevelIteration

22

Using Harmony spread operator and arrow functions:

var range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);

Example:

range(10, 15);
[ 10, 11, 12, 13, 14, 15 ]
0
19

You can use lodash or Undescore.js range:

var range = require('lodash/range')
range(10)
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Alternatively, if you only need a consecutive range of integers you can do something like:

Array.apply(undefined, { length: 10 }).map(Number.call, Number)
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

In ES6 range can be implemented with generators:

function* range(start=0, end=null, step=1) {
  if (end == null) {
    end = start;
    start = 0;
  }

  for (let i=start; i < end; i+=step) {
    yield i;
  }
}

This implementation saves memory when iterating large sequences, because it doesn't have to materialize all values into an array:

for (let i of range(1, oneZillion)) {
  console.log(i);
}
3
  • The ES6 part is now the correct answer to this question. I would recommend removing the other parts, which are covered by other answers.
    – joews
    Nov 8, 2015 at 15:24
  • generators are somewhat strange if used outside a loop though: x=range(1, 10);//{} x;//{}// looks like an empty map WTF!?! x.next().value;// OK 1 ;x[3] // undefined, only with real array
    – Anona112
    Dec 8, 2016 at 20:06
  • @Anona112 you can use Array.from to convert generators to array instances and inspect the output. Dec 8, 2016 at 21:43
18

Did some research on some various Range Functions. Checkout the jsperf comparison of the different ways to do these functions. Certainly not a perfect or exhaustive list, but should help :)

The Winner is...

function range(lowEnd,highEnd){
    var arr = [],
    c = highEnd - lowEnd + 1;
    while ( c-- ) {
        arr[c] = highEnd--
    }
    return arr;
}
range(0,31);

Technically its not the fastest on firefox, but crazy speed difference (imho) on chrome makes up for it.

Also interesting observation is how much faster chrome is with these array functions than firefox. Chrome is at least 4 or 5 times faster.

1
  • Note that this was compared against range functions that included a step size parameter
    – binaryfunt
    Aug 24, 2017 at 13:01
18

range(start,end,step): With ES6 Iterators

You only ask for an upper and lower bounds. Here we create one with a step too.

You can easily create range() generator function which can function as an iterator. This means you don't have to pre-generate the entire array.

function * range ( start, end, step = 1 ) {
  let state = start;
  while ( state < end ) {
    yield state;
    state += step;
  }
  return;
};

Now you may want to create something that pre-generates the array from the iterator and returns a list. This is useful for functions that accept an array. For this we can use Array.from()

const generate_array = (start,end,step) =>
  Array.from( range(start,end,step) );

Now you can generate a static array easily,

const array1 = generate_array(1,10,2);
const array1 = generate_array(1,7);

But when something desires an iterator (or gives you the option to use an iterator) you can easily create one too.

for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
  console.log(i)
}

Special Notes

15

This may not be the best way. But if you are looking to get a range of numbers in a single line of code. For example 10 - 50

Array(40).fill(undefined).map((n, i) => i + 10)

Where 40 is (end - start) and 10 is the start. This should return [10, 11, ..., 50]

15

Not implemented yet!

Using the new Number.range proposal (stage 2):

[...Number.range(1, 10)]
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
13
(from, to) => [...Array(to - from)].map((_,i)=> i + from)
13

In case want to use the range only to repeat a process n times u could simply use this code

[...Array(10)].map((item, index) => ( 
    console.log("item:", index)
))
4
  • This method only works if your range starts at 0. Mar 30 at 19:57
  • The goal of this option is clearly mentioned repeat the process n times not to stimulate python range method necessarily, this is helpful in react especially to quickly create n items inside a component. Mar 31 at 15:27
  • The asker specifically requested a function that could accept upper and lower bounds. This option does not accept a lower bound and therefore does not answer the question. Mar 31 at 19:39
  • Do you think that the asker will give an interest to my answer it is published 12 years ago! new answers are to help new quite similar questions, like myself I was looking for a way to create n component inside react app so I was looking for custom range, and I guess some people does and since this question will be the most floating once you search about such a way so it would be very helpful to share an answer here and mostly it is not against the global idea, got me? Think about the value ;). Mar 31 at 19:53
12

An interesting challenge would be to write the shortest function to do this. Recursion to the rescue!

function r(a,b){return a>b?[]:[a].concat(r(++a,b))}

Tends to be slow on large ranges, but luckily quantum computers are just around the corner.

An added bonus is that it's obfuscatory. Because we all know how important it is to hide our code from prying eyes.

To truly and utterly obfuscate the function, do this:

function r(a,b){return (a<b?[a,b].concat(r(++a,--b)):a>b?[]:[a]).sort(function(a,b){return a-b})}
2
  • 4
    Short != simple, but simpler is better. Here's an easier to read version: const range = (a, b) => (a>=b) ? [] : [a, ...range(a+1, b)], using ES6 syntax
    – nafg
    Dec 26, 2016 at 7:27
  • 1
    @nafg: const range = (a, b, Δ = 1) => (a > b) ? [] : [a, ...range(a + Δ, b, Δ)];. Also upvoting the whole answer for the comment.
    – 7vujy0f0hy
    Dec 29, 2017 at 16:38
12

I would code something like this:

function range(start, end) {
    return Array(end-start).join(0).split(0).map(function(val, id) {return id+start});
}  

range(-4,2);
// [-4,-3,-2,-1,0,1]

range(3,9);
// [3,4,5,6,7,8]

It behaves similarly to Python range:

>>> range(-4,2)
[-4, -3, -2, -1, 0, 1]
12

My personal favorite:

const range = (start, end) => new Array(end-start+1).fill().map((el, ind) => ind + start);
1
  • maybe better [...Array(end-start+1)].map((el, ind) => ind + start); ?
    – Simon Zyx
    Mar 3, 2021 at 10:49
12

ES6

Use Array.from (docs here):

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

A rather minimalistic implementation that heavily employs ES6 can be created as follows, drawing particular attention to the Array.from() static method:

const getRange = (start, stop) => Array.from(
  new Array((stop - start) + 1),
  (_, i) => i + start
);
2
  • As a side note, I've created a Gist in which I made an "enhanced" getRange() function of sorts. In particular, I aimed to capture edge cases that might be unaddressed in the bare-bones variant above. Additionally, I added support for alphanumeric ranges. In other words, calling it with two supplied inputs like 'C' and 'K' (in that order) returns an array whose values are the sequential set of characters from the letter 'C' (inclusive) through the letter 'K' (exclusive): getRange('C', 'K'); // => ["C", "D", "E", "F", "G", "H", "I", "J"]
    – IsenrichO
    Mar 14, 2017 at 3:10
  • you don't need the new keyword Mar 14, 2019 at 17:41
9

Though this is not from PHP, but an imitation of range from Python.

function range(start, end) {
    var total = [];

    if (!end) {
        end = start;
        start = 0;
    }

    for (var i = start; i < end; i += 1) {
        total.push(i);
    }

    return total;
}

console.log(range(10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
console.log(range(0, 10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(range(5, 10)); // [5, 6, 7, 8, 9] 
1
  • +1 for the fastest. with an array of -36768 - 36768, took 3ms, 2nd place was 13 ms and has IDE red lines.
    – mjwrazor
    May 9, 2017 at 21:12
9

The standard Javascript doesn't have a built-in function to generate ranges. Several javascript frameworks add support for such features, or as others have pointed out you can always roll your own.

If you'd like to double-check, the definitive resource is the ECMA-262 Standard.

4
  • While I'm sure a perfectly good answer in 2010, this should no longer be considered the best approach. You should not extend built in types, like Prototype.js tended to do 👍 Jul 19, 2018 at 3:34
  • @DanaWoodman thanks for bringing this up - I've updated the answer to take out the reference to Prototype.js since that is indeed pretty much obsolete in 2018 Jul 19, 2018 at 5:39
  • 66
    Well this didn't help at all.
    – Pithikos
    Apr 1, 2019 at 19:09
  • 3
    @Pithikos I see this question has been edited since it was originally asked and the OP wanted to know if there is a native range function in JS. Apr 3, 2019 at 2:57
9

This one works also in reverse.

const range = ( a , b ) => Array.from( new Array( b > a ? b - a : a - b ), ( x, i ) => b > a ? i + a : a - i );

range( -3, 2 ); // [ -3, -2, -1, 0, 1 ]
range( 1, -4 ); // [ 1, 0, -1, -2, -3 ]
9

d3 also has a built-in range function.

See https://github.com/d3/d3-array#range:

d3.range([start, ]stop[, step])

Generates an array containing an arithmetic progression, similar to the Python built-in range. This method is often used to iterate over a sequence of numeric or integer values, such as the indexes into an array. Unlike the Python version, the arguments are not required to be integers, though the results are more predictable if they are due to floating point precision. If step is omitted, it defaults to 1.

Example:

d3.range(10)
// returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2
  • I never knew D3 existed. Not going to use their range method but will be using this package.
    – mjwrazor
    May 9, 2017 at 19:24
  • Thank you so much. I use D3 and was looking for a native JS method, not knowing that I D3 offers it already.
    – cezar
    Jul 1, 2019 at 7:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.