How to use array() constructor In Javascript

In this method, we use the JavaScript array() constructor to create an array. It will just create an array without any value with a given size. However, the values of the array will be undefined.

Example: In this example, we are using an array constructor for the formation of an array.

Javascript
let arr = new Array(5);
console.log(arr.length);
console.log(arr)

Output
5
[ <5 empty items> ]

Create an array of given size in JavaScript

Creating an array of a specific size can be achieved through various methods, each suited to different situations. In this article, we will explore several approaches to creating arrays of a desired size, accompanied by examples for each method.

Below are the following ways:

Table of Content

  • Using JavaScript array() constructor
  • Using apply() and map() Methods
  • Using JavaScript Array.from() Method
  • Using for loop
  • Using the spread syntax with Array.fill()

Similar Reads

Method 1: Using JavaScript array() constructor

In this method, we use the JavaScript array() constructor to create an array. It will just create an array without any value with a given size. However, the values of the array will be undefined....

Method 2: Using apply() and map() Methods

We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined....

Method 3: Using JavaScript Array.from() Method

In ES6, we got something new called JavaScript Array.from() function, by which we can create an array of a given size....

Method 4: Using for loop

Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false....

Method 5: Using the spread syntax with Array.fill()

Using the spread syntax `[…Array(size)]`, where size is the desired array length, creates an array of that size. Combining it with `.fill(0)` fills the array with the specified value (`0` in this case), resulting in an array of the desired size filled with the specified value....