Learn how to create an array of a specified size in JavaScript with the step-by-step guide. There are several ways to create an array of a given size. Here's a brief description of each approach to create an array of a given size in JavaScript.
1. Array Constructor with fill() Method
This approach uses the Array constructor along with the fill() method to create an array of a specified size and initialize all elements with a specified value (here, 0).
const size = 5;
const newArray = new Array(size).fill(0);
// Output: [ 0, 0, 0, 0, 0 ]
console.log(newArray);
2. Using Array.from() Method
The Array.from() method creates a new array from an iterable object. In this case, an object with the length property is used to define the size, and a mapping function initializes each element with a specified value (here, 0).
const size = 5;
const newArray = Array.from({ length: size }, () => 0);
// Output: [ 0, 0, 0, 0, 0 ]
console.log(newArray);
3. Using Array.map() Method
This approach combines the use of Array.from() and the map() method to create an array of a specified size. The mapping function initializes each element with a specified value (here, 0).
const size = 5;
const newArray = Array.from(Array(size), () => 0);
// Output: [ 0, 0, 0, 0, 0 ]
console.log(newArray);
4. Using for Loop
A traditional for loop is used to iterate a specified number of times (size) and push a specified value (here, 0) into the array during each iteration.
const size = 5;
const newArray = [];
for (let i = 0; i < size; i++) {
newArray.push(0);
}
// Output: [ 0, 0, 0, 0, 0 ]
console.log(newArray);
5. Using Array.keys() Method
The spread operator (...) is used with Array.keys() to create an array of indices, and then the map() method is used to initialize each element with a specified value (here, 0).
const size = 5;
const newArray = [...Array(size).keys()].map(() => 0);
// Output: [ 0, 0, 0, 0, 0 ]
console.log(newArray);