Introduction To Arrays & Object Types

Open the project folder

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

01.JavaScript Basics > 11.Introduction-to-arrays

Object types: Array

In JavaScript, there are 2 groups we can place out types into that we touched on earlier. There are primitive and object types.

The previous data types we have looked at, such as string, number, boolean, undefined and null, all fall into a group call primitive types.

There is also bigint and symbol which we have not yet covered.

We are now going to look at object types, the first one is an array. The previous primitive values we have looked at store one string of text, or one number for example, but an array can hold multiple values.

If you think of a shopping list, or a to-do list, or generally any list with multiple values, an array is ideal for this kind of data.

Let’s look at an array example in the project folder.

Array values are held inside of square brackets, and can hold any value type, including primitives, objects, and even other arrays:

['age', 37, true, ['hey', 'you']];

If we wanted to store pizza ingredients, it could look like this:

['dough', 'cheese', 'sauce', 'pepperoni'];

But what now? How do we read or access these values? As we do with any other values, we can store them in a variable:

let pizza = ['dough', 'cheese', 'sauce', 'pepperoni'];
document.getElementById('title').innerText = pizza;

Accessing array values

Reading individual array values are simple, array values are numbered from position zero, and this is called the index position:

document.getElementById('title').innerText = pizza[1];

Since they begin at zero, the above index number of 1 will be the second value in the array. We can also access the number of items inside of the array by using the length property:

document.getElementById('title')
  .innerText = `This pizza has ${pizza.length} ingredients`;

Introduction to array methods

Arrays also have methods available which we can use to perform some common tasks, such as pushing new items to the array, and removing values. We can also check if the array includes a certain value. And it is this includes method we will now look at:

let pizza = ['dough', 'cheese', 'sauce', 'pepperoni'];
let hasPepperoni = pizza.includes('pepperoni');
document.getElementById('title').innerText = hasPepperoni;

This includes method takes in a value, in our case the string of pepperoni, and returns a true or false value, depending on if the value was present in the array. This returned Boolean value is then stored into the hasPepperoni variable for later use.

There are many of these methods available, and there is a dedicated array section coming up later.