The Array Constructor

Open the project folder

In our starter files, open the index.html page from this lessons folder:

02.Arrays-In-More-Depth > 01.The-array-constructor

Array literal

We learned in the last section that arrays fall into the Object type category, and they are a special type of object which is like a list, and we can access any of the values by the index position.

We created an array just like this, and as you can see by the comment, this is what is called an array literal:

 // Array Literal
const pizza = ['dough', 'pepperoni', 'cheese', 'sauce'];

We declare we want an array by using the square brackets, and we add the values we initially want.

We can also use typeof to confirm this is a type of object:

const pizza = ['dough', 'pepperoni', 'cheese', 'sauce'];
console.log(typeof pizza);

Array constructor

There is another way to create an array, and that is by using the Array constructor. This can be used to create an empty array to add to later, an array with empty spaces, and we can also add initial values to it.

To do this, we use the new keyword to create a new Array object:

// Array Constructor
const ingredients = new Array();
console.log(ingredients);

As you may expect, this will log an empty array. We can add values to this array inside of the brackets:

const ingredients = new Array('dough', 'cheese');

This is just the same as creating a literal version like earlier, they both result in the same outcome. If we wanted, we can also replace these values, and set up the initial length of the array:

const ingredients = new Array(5);

This will create an array with 5 empty values. The array length is not fixed at 5, it is just the starting value, we can add to it using the push method.

This push method will add a new value to the end of the array:

ingredients.push('peppers');

This will push the value of peppers onto the end of the 5 empty slots. If we want to replace one of these slots, we can use the splice method. Let’s say we wanted to replace the third empty slot, splice takes in up to 3 values, called parameters:

// index position to go to, remove 1 item
ingredients.splice(2, 1);

This will remove 1 item at position 3, since arrays begin at zero, we use number 2.

To replace this removed slot with a new value, we add a third parameter:

ingredients.splice(2, 1, 'onions');

This leaves us with slots 1 and 2 empty, the new value in position 3, and slots 4 and 5 still empty.

These push and splice methods are useful when working with arrays, and we will cover lot's more in this section. For the remainder of this course, most examples will use the array literal version, but it is useful to know these alternatives exist.