Array Constructor in Javascript

An array constructor is a constructor function that allows us to create a new JavaScript Array. Every Javascript array also has a constructor property, which points to the constructor function.

How to use Array Constructor

JavaScript has a global Array constructor function. We use the new keyword to invoke it. It creates a new array using the arguments. Except when it has only one argument which is numeric, then it will create an array with a length equal to the provided argument.

The basic syntax is as follows.

The following example creates arrays of books with 4 elements.

The “Ulysses” is stored at index 0, “Don Quixote” at index 1, etc.

Note that calling the Array function without new also returns the array without any side effects. However, you should not invoke a constructor function without a new keyword.

Array Constructor with one numeric argument

The following code creates an array with two elements ( 5 & 10)

But if you pass only one numeric argument, then it will create an empty array with a length equal to the argument. For example, new Array(5) will create an array with length 5 but without any elements. Such an array is known as Sparse Array

The above is the same as the following array literal syntax

The number passed as a string will create only one element.

If you pass a -ve number, the Javascript will throw an error. In fact, if we pass a single numeric argument whose value is not between 0 and 232 – 1 (inclusive) an error will be thrown

This is will create an array with two elements

Creates an empty array. i.e array with no elements & zero length

The following creates an array with two elements.

Constructor Property

Every Array has a constructor property, which returns the constructor function that created the Array. It actually returns the Array Constructor function, because all arrays are created using that constructor function.

arr is the Array with one element. We can access its constructor property using arr.constructor

Since it is a constructor function, we can use it to create new arrays

Reference

Array

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top