Array Constructors
In JavaScript, the Array() constructor is used to create a new array object. The Array() constructor can be used in two ways:
Array() with no arguments
This creates an empty array with no elements.
const arr = new Array();
Array() with one or more arguments
This creates an array with one or more elements. The elements can be of any data type, and they are separated by commas inside the parentheses.
const arr = new Array(element1, element2, ..., elementN);
Alternatives
Alternatively, you can also create an array using array literal notation, which is a shorthand way of creating an array without using the Array() constructor.
const arr = [element1, element2, ..., elementN];
Both methods are valid and have the same result.
It's important to note that the Array() constructor can also be used to set the length of an array. For example, if you pass a single argument to the Array() constructor, that argument is treated as the length of the array.
const arr = new Array(5); // creates an array with a length of 5, but no elements
Array() constructor is a useful tool for creating and initializing arrays in JavaScript. However, the array literal notation is often preferred because it is shorter and easier to read.
Edit this page on Github
This page was updated on -
Found an error or have feedback on our docs?
Create an issue on GitHub and let us know! Your input helps improve our documentation for everyone in the community.
Report error, send feedback on Github