Arrays with Javascript
An array is like a variable it stores information. It can hold a number, a string or a boolean value.
The problem with simple variables is that each one only stores one value. For example, if you want to keep track of items in a shopping cart. You’d need to create a new variable of every item in the cart. Even worse you would have to declare variables in your program before it even runs and how would you ever know the number of items one user would ever buy. That’s where arrays come in.
An array is a flexible method of storing information. It can hold a single string, 100 numbers, booleans, even more arrays. The reason an array is flexible is that you don’t have to know ahead of time how many things you need to add to it. You can remove and add values as your program runs.
Creating a Array
const cart = [ 'bread', 'milk', 'cookies' ];
Creating an array is simple you start with the let or const keyword then the a name for the array. This is just like creating a simple variable. You follow the same rules and naming conventions. The equals sign assigns a value to the variable and the semicolon ends the statement, just like you’d use with a simple variable. The bracket represents an array. Inside them, we add a comma-separated list of values. This can be strings, numbers, booleans, arrays or a combination of all of these. When you have dozens or more values in an array its commons to break that array up over multiple lines, with each item in the array on a single line. Javascript isn’t too picky about whitespace or line breaks so this works makes your code easier to read.
Accessing Items in an Array
Now that we know how to create array how do we use it? With a simple variable, we can just print the value with document.write or the console.log with the variable name attached. With arrays however its more than one value its a list of multiple values. To access a single value within an array, we use what’s called an index value, that’s just a number that tells us the position of the value in the list.
Think of arrays like a numbered list. To get a value in the list you need to call the number of the value. Arrays don’t start at 1 however. The first item in an array is 0. Eg in our shopping list with three items. Milk has the 0 index, eggs have the 1 index, and bread has the 2 index. To access those values you type the name of the array followed by square brackets and its index value.
const cart = [ 'bread', // 0 Index 'milk', // 1 Index 'cookies' // 2 Index ]; console.log(cart[0]); //prints bread
You can test this code out yourself by opening the Javascript console in your browser. I use chrome as its the browser I’m most familiar with plus its the most popular.
- Windows: Ctrl + Shift + J
- Mac: Cmd + Option + J
One of the best things about arrays is that you can add, remove and update the array values within the program. For example, someone visiting your online store can add or remove items in their cart. From a programming perspective, the cart is an array. As the user shops, they add and remove items to the cart array.
Adding Data to Arrays
We can already see why arrays are one of the most used ways to store information in Javascript. There are many ways to work with them. Way too many for me to cover in one blog post. But if you head over to The Mozilla Developer Network you’ll find everything thing you need to know on arrays. When on the website find the sidebar on the left. You will see the list of properties and methods of the array object. The length property, for example, contains the number of items in an array.
const cart = [ 'bread']; console.log(cart.length); // returns 1
The length property is like a variable for that array. As you add and remove items to the array the length variable will increase or decrease. The easiest way to add items to an array is to use the array objects push method. Methods are actions you perform on an object, The push method lets you add one or more items to the end of an array. To use the method you simply type the arrays name followed by a period with the word push and a set of brackets with the values you want to add. Like the sample below.
const animals = ['pigs', 'goats', 'sheep']; animals.push('cows'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"]
Another benefit of the push method is that you can add more than one item to the end of the array. You simply add a comma as a separator followed by the next value.
animals.push('chickens', 'cats', 'dogs'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
You can also add values to the beginning of an array by using the unshift method. The syntax is the same as the push method but it adds the values starting at the 0 index value. You can also add more than one value to the array.
const items = ['Hat', 'Ball', 'Shoes']; items.unshift('Socks','Scarf'); // expected output: ['Socks', 'Scarf', 'Hat', 'Ball', 'Shoes']
Removing Items From Arrays
Just like the two methods of adding values to an array Javascript provides two methods for removing items from an array using pop or shift methods. The pop method is the opposite of push, while push adds items to the end of an array, pop pops the last item off and array.
const numbers = [ 1, 2, 3, 4, 5, 6 ]; let last = numbers.pop(); let first = numbers.shift();
If we ran the pop method on the numbers array the last item ‘6’ would be removed from that array. The pop method returns the value of the last item as well. Meaning you can use pop to get the last item in the array. The shift method is similar except it removes the first item from the array. If we used it on the number array it would return 1.
Using For Loops with Arrays
Because arrays can hold a limitless number of values sometimes you will need to get those values. To do that we need to cycle over each value in the array so you can work with it. The best way to do this is to use a for loop. A for loop repeat’s actions over & over until a condition is met. Here is an example of a basic for loop.
const cart = ['bread','milk','cookies']; for(let i = 0; i < cart.length; i+=1){ console.log(cart[i]); }
Before the loop runs a counter variable i is set to 0. Each time through the loop 1 is added to i & the program logs the array value according to the value of i. i starts at 0 and so does our array index so its perfect for checking our array. As soon as i is no longer less than the length of the array the loop ends. We used the length of the array instead of a fixed number as the comparison value because we can’t always be sure of the length of the array. This way we know the loop executes the same number of times as there are items in our array.
Useful Array Methods
So far in this blog post, we’ve looked at methods like push, unshift, pop and unshift. These are just a few of the array methods that are available. There are many other useful methods such as the join. The join method takes an array and returns a string with all the items separated by a supplied character. This is a great way to display the items in an array on a single line.
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join(, )); // expected output: "Fire, Air, Water"
You can pass any character to the join method, we’ve used a comma. You can actually pass more than one character in our example we’ve passed two characters the comma and space this makes our join output much easier to read. Another useful method is concat. You use it to add one array to another. For example, say you had an array of letters and you get another list containing more letters. You can combine these arrays to create a more update array of letters.
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
The concat method takes the first array and adds the second array. If you wanted the second array to be first you would swap the two arrays around in the concat method. The concat method doesn’t change the two original arrays. One other useful method is the indexOf. This method lets you search an array for a particular value. If the value is in the array then the value position is returned. For example, if you had an array of animals. To search for a value in the list you use the indexOf method like below.
const animals = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(animals.indexOf('bison')); // expected output: 1 console.log(animals.indexOf('ant')); // expected output: 0 console.log(beasts.indexOf('giraffe')); // expected output: -1
Because bison is the second item in the array the 1 index value is returned. If we searched for ant instead the 0 index value will be returned. If the value is not in the array like the giraffe value the method returns the value -1.
Multi-Dimensional Arrays
As we know arrays can hold strings numbers and boolean values but they can also hold other arrays or an array of arrays, aka array inception. The name technical term for this is multi-dimensional arrays. Think of it like a spreadsheet the outer array is the spreadsheet itself, each row represents one array and each column represents one array value. See the example below.
const activities = [ ['Work', 9], ['Eat', 2], ['Commute', 2], ['Play Game', 2], ['Sleep', 7] ];
When creating a multi-dimensional you first create the outer array then place another set of brackets inside that array. Each array must be separated by a comma. That means your adding another array inside that initial array. You then add your values separated by commas in our case the activity name and the time needed to complete that activity.
console.log(activities[0][0]); // expected output: Work console.log(activities[0][1]); // expected output: 9 console.log(activities[4][1]); // expected output: Sleep
Once we have our array we want to access the information. To get the value for one activity we use the index notation we covered this earlier. So to get the first activity in our array we use activities[0], the second value with activities[1]. Because each of those represents another array you can access individual values in that array using another index value. In other words, the first activity name is index position 0 and the time takes to complete that activity is represented by 1. We can use a more effective way to access the values in the array by using the for a loop.
const activities = [ ['Work', 9], ['Eat', 2], ['Commute', 2], ['Play Game', 2], ['Sleep', 7] ]; for (let i = 0; i < activities.length; i+=1) { console.log(activities[i][0] + ' takes ' + activities[i][1] + ' hours'); }
It works the same way as looping over a single array but to access an item in a multi-dimensional array you use a pair of extra brackets and an extra index value.
Wrapping Up
This is a quick look at arrays in javascript. Hopefully, it helps you out with understanding them just as it did for me. You can take a look at my big quiz & stock level checker programs to see all that we’ve covered in action on Codepen. Why not create your own and see if you can create one too. Thank you for reading, and being part of this conversation. If you would like to chat or have any questions drop me an email I’m always happy to talk