What Is an Array?

An array is a way to store a collection of multiple items under a single variable name. This section introduces how to create, delete and access array elements.  Think about the following as you read the article:

  • How are array elements accessed?
  • What methods are used to access the elements of an array?
  • How would you convert a string into an array?


Removing items

To remove the last item from the array, use pop().

const cities = ["Manchester", "Liverpool"];
cities.pop();
console.log(cities); // [ "Manchester" ]

The pop() method returns the item that was removed. To save that item in a new variable, you could do this:

const cities = ["Manchester", "Liverpool"];
const removedCity = cities.pop();
console.log(removedCity); // "Liverpool"

To remove the first item from an array, use shift():

const cities = ["Manchester", "Liverpool"];
cities.shift();
console.log(cities); // [ "Liverpool" ]

If you know the index of an item, you can remove it from the array using splice():

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]

In this call to splice(), the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 2);
}
console.log(cities); // [ "Manchester", "Carlisle" ]