Creating and initializing arrays
Declaring, creating, and initializing an array in JavaScript is straightforward, as shown in the following example:
let daysOfWeek = new Array(); // {1}
daysOfWeek = new Array(7); // {2}
daysOfWeek = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); // {3}
// preferred
daysOfWeek = []; // {4}
daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; // {5}
We can:
- Line
{1}
: declare and instantiate a new array using the keywordnew
– this will create an empty array. - Line
{2}
: create an empty array specifying the length of the array (how many elements we are planning to store in the array). - Line
{3}
: create and initialize the array, passing the elements directly in the constructor. - Line
{4}
: create an empty array assigning empty brackets...