Search code examples
javascriptvariablesrangeintervals

Set a range of numbers as a variable (Javascript)


Let's say I want a variable to contain numbers from 1 to 100. I could do it like this:

var numbers = [1,2,3,4,...,98,99,100]

But it would take a bunch of time to write all those numbers down. Is there any way to set a range to that variable? Something like:

var numbers = [from 1, to 100] 

This might sound like a really nooby question but haven't been able to figure it out myself. Thanks in advance.


Solution

  • In addition to this answer, here are some ways to do it:

    for loop:

    var numbers = []
    for (var i = 1; i <= 100; i++) {
        numbers.push(i)
    }
    


    Array.prototype.fill + Array.prototype.map

    var numbers = Array(100).fill().map(function(v, i) { return i + 1; })
    

    Or, if you are allowed to use arrow functions:

    var numbers = Array(100).fill().map((v, i) => i + 1)
    

    Or, if you are allowed to use the spread operator:

    var numbers = [...Array(100)].map((v, i) => i + 1)
    


    However, note that using the for loop is the fastest.