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:

1,2,3,4,5,6,7,8,9

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:

1,2,3,4,5,6,7,8,9

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

Here is a full example.


Hi, I'm Renat 👋

 


HTML

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

JavaScript

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

var numbers = generateArrayOfNumbers(10);

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

Output

1,2,3,4,5,6,7,8,9

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

Want to share this with your friends?
👉renatello.com/javascript-array-of-numbers

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

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

2 Comments