How to create an array of numbers in JavaScript

in Code Write a comment

In this tutorial, you’ll learn how to generate an array of numbers in JavaScript in one line of code.

It’s a very handy function that you can use in your projects. For example, you need to generate a list of 10 numbers from 1 to 9, so that the output looks like:


You can use the function below to do that.

function generateArrayOfNumbers (numbers) {
  return [...Array(numbers).keys()].slice(1)

generateArrayOfNumbers(numbers) will generate and return N-numbers that you pass to this function as a parameter.

E.g. if you call generateArrayOfNumbers(10), the output will be:


This function uses spread operator (three dots in JavaScript), and an ES6 keys() method.

Here is a full example.


<div id="numbers"></div>


function generateArrayOfNumbers (numbers) {
  return [...Array(numbers).keys()].slice(1)

var numbers = generateArrayOfNumbers(10);

document.getElementById('numbers').innerHTML = numbers;



If you find this post useful, please let me know in the comments below. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other JavaScript tutorials, e.g. generate an array of years in JavaScript.

Incoming search terms:

Write a Comment