Arrays

An array is a variable that can hold more than one item, it holds a list of items. They are "list-like" objects. An array can store diffrent types of variables, including numbers, strings, objects and even other arrays.

Declaring an Array

Let us declare an array storing a list of names.

const names = ['Sade', 'Jimmy', 'Frank', 'Willheimena', 'Asante', 'Josephine'].

This array shown stores a list of names. How many names are stored in the array?

The Length of an Array

We can find the length of an array by using the length property. There are six items in this array.

Try it!

const names = ['Sade', 'Jimmy', 'Frank', 'Willheimena', 'Asante', 'Josephine']
let length = names.length;
console.log(length);

Accessing an Array

The items in an array are numbered, starting from 0. This number is called an index. We access arrays using their index. We specify the index in a pair of square brackets, after specifying the name of the array. For example, names[2], will return Frank. Remember that we start counting the index of the array from 0.

const names = ['Sade', 'Jimmy', 'Frank', 'Willheimena', 'Asante', 'Josephine'];
console.log(names[2]);

Modifying an Array

We can modify the content of an array using it's index number and the assignment operator. Let's see how that works. Let us change the name Sade to Folasade. First we need to get it's index, what is the index of Sade in the names array?

const names = ['Sade', 'Jimmy', 'Frank', 'Willheimena', 'Asante', 'Josephine'];
names[0] = "Folasade";

//Let's print the entire array to see the change
console.log(names)

Multidimensional Array

When you have an array inside another array, it is called a multidimensional array. We can access the items in a multidimensional array by chaining square brackets together. Let's see an example.

Array Methods

Different array methods exist to manipulate and work with arrays. For example, to find the index of items in an array, use the indexOf() function. You simply specify the value of the item, if that item exists, the index is returned, otherwise, -1 is returned.

Try it!

const names = ['Sade', 'Jimmy', 'Frank', 'Willheimena', 'Asante', 'Josephine'];

//this returns 5
lastName = names.indexOf("Josephine");
console.log(lastName);

//this returns -1
noName = names.indexOf('Salewa');
console.log(noName);

Other array methods include:

  • push(): to add items to the end of the array.
  • unshift(): to add an item to the start of the array.
  • pop(): to remove the last item from the array.
  • shift(): to remove the first item from the array.
  • splice(): to remove an item from a particular position, using its index.
  • split(): convert a string to an array.