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?
Adding items
To add one or more items to the end of an array we can use
push()
. Note that you need to include one or more items that you want to add to the end of your array.
const cities = ["Manchester", "Liverpool"]; cities.push("Cardiff"); console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ] cities.push("Bradford", "Brighton"); console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]
The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
const cities = ["Manchester", "Liverpool"]; const newLength = cities.push("Bristol"); console.log(cities); // [ "Manchester", "Liverpool", "Bristol" ] console.log(newLength); // 3
To add an item to the start of the array, use unshift()
:
const cities = ["Manchester", "Liverpool"]; cities.unshift("Edinburgh"); console.log(cities); // [ "Edinburgh", "Manchester", "Liverpool" ]