JavaScript provides us with a handful of types to best represent the variety of values we will be dealing with. We have the catch-all Object for storing key/value pairs, the Number for storing...um...numbers, String for storing text, Boolean for true/false values, and so on. A common sort of value we will be dealing with revolves around lists and collections. We may want to represent a list of names, numbers, addresses, DOM elements, and more. Storing and dealing with these list-looking kinds of data requires a very particular set of skills. That skillful Liam Neeson-looking ninja is the Array type. Starting with this article, we will get a gentle introduction into what arrays do and quickly dive deeper in follow-up articles into all the various mischief arrays help us accomplish...very skillfully!
Onwards!
Let’s start at the very beginning. To use an array, we must first create one. The most common way to create an array is to declare a variable and initialize it to a pair of opening and closing brackets:
let myArray = [];
I know that it looks weird, but it works! In this line, we are declaring a variable called myArray and initializing it to an empty array:
When we say an array is empty, what we mean is that our array isn't storing any items. There are several ways to have our array store items. One way is by creating our array with some items prepopulated. The way we do that is by specifying the items we want to create our array with inside the angle brackets:
let letters = ["a", "b", "c"];
When this code runs, our letters array gets created with the letters a, b, and c already a part of its contents:
Once we have created an array, the real party can begin! In the next section, we are going to look at some (possibly more!) common ways to add items into our array and balance it out with some ways to remove items as well.
To kick your array skills into the stratosphere, everything you need to be an arrays expert is available in this book.
BUY ON AMAZONAfter creating our array, we will often find ourselves wanting to add or remove items from it as part of our application just doing its thing or us interacting with it.
To add items to our array, we have the push and unshift methods. The push method adds items to the end of our array as shown below:
let names = ["bar", "foo", "zorb"];
names.push("blarg");
console.log(names); // ["bar", "foo", "zorb", "blarg"]
After this code runs, our names array will look as follows:
The unshift method adds items to the beginning of our array:
let names = ["bar", "foo", "zorb"];
names.unshift("blarg", "beep");
console.log(names); // ["blarg", "beep", "bar", "foo", "zorb"]
Notice that we added blarg and beep, and they found themselves in the first and second positions in our array:
In both cases, when we are adding items to our array using either push or unshift, the new length (aka count) of all the items in our array gets returned. This may come in handy when needing to know how big our array is after adding or removing items.
Just like with adding, we have two ways of removing items from our array. We have the pop method that removes the last item from our array, and we have the shift method that removes the first item from our array. Below is pop in action:
let numbers = [0, 1, 2, 3, 4, 5];
numbers.pop();
console.log(numbers); // [0, 1, 2, 3, 4]
Notice the last item in our numbers array has been removed:
The other way to remove an item is via the shift method:
let numbers = [0, 1, 2, 3, 4, 5];
numbers.shift();
console.log(numbers); // [1, 2, 3, 4, 5]
When using shift, it is the first item that gets removed in this case:
When calling either pop or shift, the item removed from our array gets returned. Below is an example of what this looks like for shift:
let numbers = [0, 1, 2, 3, 4, 5];
let removedItem = numbers.shift();
console.log(numbers) // 1, 2, 3, 4, 5;
console.log(removedItem); // 0;
The removedItem variable stores our removed item, which is the number 0.
While adding and removing items is something we'll do frequently, not everything we will be doing will involve those two operations. Most of the time, we'll just be reading the values stored by our array items instead. The way to read the contents of our array is by accessing them by their index position. Let's say we have the following greetings array:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
Our greetings array has five items. The index position (also referred to as index values) is a number indicating the position of each item in our array. The first item in our array will start with an index position of 0, and the index position goes up by 1 for each subsequent item:
To read the first item in our array, we will reference our greetings array and pass in the index position of 0 as an argument using the brackets:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
let first = greetings[0];
console.log(first); // "hi"
When we read an item, our array does not get modified. Nothing is added. Nothing is removed. The index positions are always fixed where the first item in our array always has a value of 0, the second item has a value of 1, and so on. If we were to remove the first item from our array, our approach for reading the first item remains the same:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
greetings.shift();
let first = greetings[0];
console.log(first); // "sup"
The only difference is that the value of our first item is going to be sup instead of hi.
Now, when working with index positions, there is an important detail about our arrays that will be really helpful to know. That detail is around how many items are actually in our array. We don't want to specify an index position that is greater than what our array can actually handle. Doing so will return a value of undefined:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
console.log(greetings[6]); // undefined
To avoid these types of situations, the way we can calculate how many items are in our array is via the length property:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
let arrayLength = greetings.length;
console.log(arrayLength); // 5
For our greetings array, the length property will return a value of 5 because we have 5 items in it. As long as the index position we are specifying stays less the total length of the array, we can be confident that we are reading from a valid spot in our array. Pretty cool, right?
Before we wrap this section up, there is one more thing I want us to look at. With our understanding of index positions and array lengths, we have all the ingredients needed to loop through our array and read every item. Take a look at the following for loop:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
for (let index = 0; index < greetings.length; index++) {
let greeting = greetings[index];
console.log(greeting);
}
When this code runs, our loop starts with the index variable set to 0, and it keeps running until it hits the last item in our array. Along the way, we are accessing the current array item (greetings[index]) and printing it to our console. Because the length of our array starts at 1 and our index position starts at 0, our array's terminating condition of index < greetings.length properly ends our loop just after it reaches our last item. Looping through an array is one of those things that we'll be doing many MANY times, so we'll have plenty of chances to see similar looking code in the future.
When we have a reference to an array item using the index position, we aren't limited to just reading the value stored by that item. We can just as easily replace the value stored by that item by assigning a new value to it. Take look at the following snippet:
let greetings = ["hi", "sup", "hello", "yo", "hey"];
greetings[2] = "hola";
console.log(greetings); // "hi", "sup", "hola", "yo", "hey"
At index position 2, we overwrite the initial hello value with hola:
When we print the array to our console, we can see the result of this replacement where we will see hi, sup, hola, yo, and hey getting printed.
What we just saw is a nice, direct case where the index position we are specifying is one our array already contains a value for. There are a handful of strange cases we can get into here - like what happens when our index position is larger than the number of items in our array, we specify a value for the index position that isn't actually a number, or we specify a negative number. That is going to covered separately in a future article, for it goes into the weeds a bit.
To find something in our array, we have the handy indexOf method. We pass in the value we are looking for, and indexOf will do the hard work of letting us know if the value exists in our array or not.
If the value exists, indexOf will return the index position of the first array item storing our result:
let friends = ["Joey", "Monica", "Ross", "Chandler", "Phoebe", "Rachel"];
let result = friends.indexOf("Chandler");
console.log(result); // 3
If the value does not exist, indexOf will return a -1:
let friends = ["Joey", "Monica", "Ross", "Chandler", "Phoebe", "Rachel"];
let result = friends.indexOf("Kramer");
console.log(result); // -1
If you have an array with the values you are looking for appearing multiple times, indexOf will only find the first entry and stop there. We will have to write some additional logic to find all instances, and that is something we'll explore later.
Another detail to note is that there is a lastIndexOf method at our disposal as well. This method is nearly identical to indexOf, but instead of finding the first matching value like indexOf does, lastIndexOf finds the last matching value instead.
There is something we should mention about arrays. We aren’t limited to storing values of only one type, such as only strings or numbers. JavaScript isn’t very strict about rules like this (unlike a strongly-typed language like Java or C#), so we can get away with doing something like the following:
let myArray = ["Hello", "🍕", 3.14, true];
Notice that myArray is being created with the strings Hello and 🍕, the number 3.14, and the boolean true as the initial values. We are effortlessly mixing data types! We can even store arrays inside an array:
let myArray = ["Hello", "🍕", 3.14, true, [1, 2, 3]];
This flexibility arrays bring with them makes them powerful, but it also means we have to be extra careful to not accidentally mix and match types if we aren't intending to.
What we just explored over the past many sections is the tip of the iceberg in terms of what arrays can do. We covered the basics and helped set the foundation for some of the more in-depth (and funner!) array related content we will be running into in the future. So...grab a drink and let's continue forward to learn more about arrays! 🤪
Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!
:: Copyright KIRUPA 2024 //--