How to make an array of JavaScript numbers from

This article shows how to convert a number to an array of numbers in JavaScript, using an example.

Making an Array of Numbers in JavaScript

Creating an array of numbers in JavaScript is a simple process that can be done with just a few lines of code. To create an array of numbers, you simply need to declare a new array and assign it to a variable. Then, you can use a for loop to fill the array with numbers.


// Declare a new array and assign it to a variable
var numbers = [];

// Use a loop to fill the array with numbers from -10 to 10
for (var i = -10; i <= 10; i++) {
  numbers.push(i);
}

console.log(numbers);
// Output: [ -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

The code above creates an array of numbers from -10 to 10 and assigns it to the variable numbers. We use the built-in push() method to add each number to the array. Once the loop is complete, the array will contain all the numbers from -10 to 10.

If you need to create an array of numbers with a larger range, you can do so by changing the starting and ending values of the loop. For example, if you need an array of numbers from 0 to 1000, you can use the following code:


// Declare a new array and assign it to a variable
var numbers = [];

// Use a loop to fill the array with numbers from 0 to 1000
for (var i = 0; i <= 1000; i++) {
  numbers.push(i);
}

console.log(numbers);
// Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 998, 999, 1000 ]

The code above creates an array of numbers from 0 to 1000 and assigns it to the variable numbers. We use the same push() method to add each number to the array. Once the loop is complete, the array will contain all the numbers from 0 to 1000.

Answers (0)