Array - The basics
Arrays are usually defined as a collection of items, often of the same type, with the ability to access each element by its index number. In many programming languages, you will find an array type as the most basic data type for storing collections, often with more advanced collections built on top of arrays, but in JavaScript, we mostly use arrays when we need to store several items in the same list.
Luckily for us, JavaScript comes with a very nice built-in object called Array for working with arrays, and a bit of syntactic sugar to make it even easier and feel more natural. In this article, we'll take a deep dive into how arrays work in JavaScript and all the possibilities they give us.
Creating an array
When you want to create an array, there are two ways. The verbose way:
let array = new Array();
And then there's the short version, which uses a bit of syntactic sugar to accomplish the same as the first approach:
let array = [];
The latter approach is the most commonly used, so we'll use that from now on. Of course, both versions only gives us an empty array with nothing in it. If we want to, we can easily change this, so that the array comes with a couple of items, like this:
let fruits = ["Apple", "Pineapple", "Banana"];
Array keys
Please be aware that JavaScript arrays are NOT associative arrays, basically meaning that the keys used to store items with are always non-negative integers (0, 1, 2...) and never anything else, like strings.
If you can use any type of object as the key for an array items, it's called an associative array, basically because you are able to "associate" the value with a relevant key instead of just an index number. This is not possible with JavaScript arrays, but it can actually be accomplished using JavaScript objects instead. We'll discuss this option later on in the tutorial when we get to objects.
Array item types
In some programming languages, where types are not as dynamic as they are in JavaScript, you are forced to create arrays based on what kind of data they should hold. So you would typically have an array of strings or an array of integers and so on.
However, with JavaScript, being dynamic as always, an array can hold pretty much anything, e.g. strings, numbers, objects and even functions, and you are free to mix and match any way you want to. Here's an example:
let array = ["Apple", 42, new Date()];
alert(array[2]);
Array length
You can always know the amount of items currently in the array by checking the length property:
let fruits = ["Apple", "Pineapple", "Banana"];
alert("Fruit count: " + fruits.length); // 3
But be aware! The length property is actually used internally by the array, to control how many items it may hold. This mostly happens behind the scenes, as the array will automatically resize itself to accommodate the amount of items you need it to hold, unless you specifically ask for an array of a certain length. You can do that by creating an Array object like this, where we basically create an array with 6 empty items:
let arr = new Array(6);
alert(arr.length); // 6
But you are also able to change the length manually, like this:
let fruits = ["Apple", "Pineapple", "Banana"];
fruits.length = 6;
alert("Array length: " + fruits.length); // 6
Even though our array only contains 3 fruits, the length property will return 6 because we overrode the length property. However, this is not something you would usually do, so for most situations, you can rely on the length property.
Accessing items
With an array defined, we can now do all sorts of things with it. One of the most basic operations would be to simply access an item based on the index. Here you have to remember that in programming, counting almost always starts with 0 instead of 1, so the first item would be at position 0, the second on position 1 and so on. With that in mind, let's try accessing the array item which contains the "Pineapple":
let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits[1]);
Notice the use of square brackets, both when we create the array, as well as when we access an item. In JavaScript, square brackets are very closely connected to arrays.
Looping over an array
We already talked about looping over an array when we discussed loops in general, but I think it deserves to be discussed here as well. Since arrays are collections of items, it makes perfect sense that you can loop through these items and access each item in turn. We can use all the types of loops made available to us by JavaScript, but especially the for and for..of loops are very relevant here.
We'll start with the for loop, which has existed through all versions of JavaScript, unlike the for..in loop, which is a more recent addition:
let fruits = ["Apple", "Pineapple", "Banana"];
for(let i = 0; i < fruits.length; i++)
alert("Fruit @ index " + i + ": " + fruits[i]);
We use several concepts already discussed here: The length property of the array, which we use to instruct the for loop how many iterations we need, and the ability to access an item by its index within a set of square brackets.
However, if you don't need the counter from the for loop, and don't care about the array indexes, you can use the for..of loop instead:
let fruits = ["Apple", "Pineapple", "Banana"];
for(let fruit of fruits)
alert(fruit);
As you can see, the for..of loop is a lot quicker to type and easier to read. If you want to know more about the various types of loops in general, just move back in this tutorial - we have several articles which goes into details on them.
Adding/removing items
We've just seen several examples of how we can instantiate an array with items already in it, but we also talked about how an array can be created without any items in it. No matter how you do it, you will soon be in a situation where you need to add or remove items after the array has been created.
push()
To add items to an array, the most common approach would be to use the push() method. It will add an item to the end of the array, like this:
let fruits = ["Apple", "Pineapple", "Banana"];
fruits.push("Pear");
alert(fruits);
And you can even specify as many new items as you want to - just separate with a comma, like this:
let fruits = ["Apple", "Pineapple", "Banana"];
fruits.push("Pear", "Mango", "Orange");
alert(fruits);
The push() method will return the new length of the array, so in case you need to know about that, you can easily use it, for instance like this:
let fruits = ["Apple", "Pineapple", "Banana"];
let fruitCount = fruits.push("Pear", "Mango", "Orange");
alert("Total fruit count: " + fruitCount);
pop()
If you need to remove an item from the array, the pop() method might be able to help you. It will simply remove the last item from the array and return the item to you, in case you need to know what was just removed. Here's an example of the pop() method in action:
let fruits = ["Apple", "Pineapple", "Banana"];
let removedFruit = fruits.pop();
alert("Removed fruit: " + removedFruit);
alert("Remaining fruits: " + fruits);
To remove multiple items, simply call the pop() method as many times as needed.
unshift() / shift()
While push() and pop() works at the end of the array, you can use the unshift() and shift() method to accomplish the exact same, but at the beginning of the array. I won't go into a lot of details, but here's an example where you can see both of them in action:
let fruits = ["Apple", "Pineapple", "Banana"];
fruits.shift();
alert(fruits); // Pineapple,Banana
fruits.unshift("Mango");
alert(fruits); // Mango,Pineapple,Banana
Multi-dimensional arrays
As we've just seen, arrays can hold any type of value like numbers, strings, dates and so on. But it can also hold another array, basically creating a multi-dimensional array. This is useful for a lot of situations - one example could be when we want to hold some kind of tabular data, where our array would hold rows of data, with each row consisting of multiple cell values:
let tableData =
[
["Name", "Age", "E-mail"],
["John Doe", 42, "john@doe.com"],
["Jane Doe", 39, "jane@doe.com"]
];
In this example, each item of the first array (tableData) holds a line in the table, and each line holds an array of data which represents the cells of the table. When we want to generate the table, we can use a loop to generate the rows, and a loop within the first loop to generate the table cells, like this:
let tableData =
[
["Name", "Age", "E-mail"],
["John Doe", 42, "john@doe.com"],
["Jane Doe", 39, "jane@doe.com"]
];
document.write("<table style=\"width: 50%;\">");
for(let row of tableData)
{
document.write("<tr>");
for(let cell of row)
{
document.write("<td>" + cell + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
Quite simple, right? And of course, there are no real limits to this: your array can hold arrays which can hold arrays which can hold arrays and so on - they can be as multi-dimensional as you need.
Summary
In this article, you have been introduced to the built-in Array object and we have talked about how to create an array, access its items and even add or remove items. But there's a lot more functionality to be found in the Array object, as we'll discover in the next article, where we dig deeper into all the Array methods.